Reputation: 6798
Hello i have problem with nested form.. im looking an hour to that and dont know what i forget ..
models/trainer.rb
class Trainer < ActiveRecord::Base
attr_accessible :telephone, :user_attributes
has_one :user
accepts_nested_attributes_for :user
end
models/user.rb
class User < ActiveRecord::Base
belongs_to :trainer
attr_accessible :email, :image_url, :name, :password_hash, :password_salt, ...
attr_accessible :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
<+ validations ...>
controllers/trainers_controller.rb
def new
@trainer = Trainer.new
@trainer.build_user
respond_to do |format|
format.html # new.html.erb
format.json { render json: @trainer }
end
end
and i can display new trainer form view (i addedd all user columns as nested) but when i hit CREATE i get
Can't mass-assign protected attributes: user
whats wrong ? thank you
edit: my db schema looks like
[users]
id
trainer_id
name
surname
[trainers]
telephone
Here i uploaded my simplify simple app if anyone was interested :) https://github.com/ScottHiscock/NestedForm
Upvotes: 0
Views: 41
Reputation: 6798
the mistake was in the view, i had
<%= f.fields_for :users do |u| %>
but correct is
<%= f.fields_for :user do |u| %>
:-)
Upvotes: 0
Reputation: 383
Also add user to attr_accessible list of trainer.rb model as follows
attr_accessible :telephone, :user_attributes
or try this
attr_accessible :telephone, :user
Upvotes: 0
Reputation: 47492
Ref accepts_nested_attributes_for
Defines an attributes writer for the specified association(s). If you are using
attr_protected
orattr_accessible
, then you will need to add the attribute writer to the allowed list.
So I think you have to do the following:
class Trainer < ActiveRecord::Base
attr_accessible :telephone, :user_attributes
Upvotes: 2