首页 > 解决方案 > 如何为 Rails 控制器中的嵌套项添加默认值?

问题描述

在我的 Rails 6 应用程序的注册表单中,可以创建一个Account带有嵌套的。User

class AccountsController < ApplicationController

  def new
    @account = Account.new
    @account.users.build(
      :owner => true,
      :language => "FR"
    )
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      redirect_to root_url, :notice => "Account created."
    else
      render :new
    end
  end

private

  def account_params
    safe_attributes = [
      :name,
      :users_attributes => [:first_name, :last_name, :email, :password, :owner, :language]
    ]
    params.require(:account).permit(*safe_attributes)
  end

end

在 new here上定义默认值的最佳方法是什么?user

现在,我hidden_fields在我的注册表单中使用默认值,从而使它们公开可用。这当然不是我想要的,因为它非常不安全。

有没有更好的方法来处理这个问题?

我知道有Rails 的 with_defaults方法,但到目前为止我无法让它在嵌套项目上工作。

标签: ruby-on-railsrubyactiverecordstrong-parameters

解决方案


尝试:

account_params[:users_attributes] = account_params[:users_attributes].with_defaults({ first_name: 'John', last_name: 'Smith'})

在创建动作的第一行


推荐阅读