Reputation: 10207
In the Sign up form of my Rails 6 application an Account
with a nested User
can be created.
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
What is the best way to define default values on the new user
here?
Right now, I use hidden_fields
for the default values in my sign up form thus making them publicly available. This is of course not what I want because it's very insecure.
Is there a better way to deal with this?
I know that there's Rails' with_defaults method but I couldn't get it to work on nested items so far.
Upvotes: 0
Views: 999
Reputation: 312
try with:
account_params[:users_attributes] = account_params[:users_attributes].with_defaults({ first_name: 'John', last_name: 'Smith'})
in first line of create action
Upvotes: 1