在我的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
在这里在新的user
上定义默认值的最佳方法是什么?
现在,我在注册表单中使用hidden_fields
作为默认值,从而使它们公开可用。这当然是我想要的[[not,因为它很不安全。
我知道有Rails' with_defaults方法,但到目前为止我无法在
嵌套项目上使用它。
account_params[:users_attributes] = account_params[:users_attributes].with_defaults({ first_name: 'John', last_name: 'Smith'})
在创建动作的第一行中