I've got a nested form (using Ryan B's nested_form gem) using a has_and_belongs_to_many to has_and_belongs_to_many setup:
Opening has_and_belongs_to_many :contacts
Contact has_and_belongs_to_many :openings
When trying to add a new contact to an opening, in this case I get:
Can't mass-assign protected attributes: new_1346666966632
for
"opening"=>{"contacts_attributes"=>{"new_1346666966632"=>{"contacts"=>{"name"=>"Test Contact",
I've added the corresponding "accepts_nested_attributes_for" and "attr_accessible", and am building the contact i.e. @opening.contacts.build and @opening.contacts.build(params[:opening][:contact_attributes]) in the controller.
Where am I going wrong? Would it be better to use a has_many through relationship here?
EDIT:
View:
<%= simple_nested_form_for @opening, :wrapper => :plain do |f| %>
<%= f.link_to_add "Add a contact", :contacts %>
<%= f.button :submit %>
<% end %>
Which uses a partial to generate fields for nested contact:
<%= f.fields_for :contacts, @opening.contacts.build do |contact_form| %>
<%= contact_form.input :name, :label => false, :input_html => { :class => 'span6' } %>
<%= contact_form.input :company, :label => false, :input_html => { :class => 'span6' } %>
<%= contact_form.input :telephone, :label => false, :input_html => { :class => 'span6' } %>
<%= contact_form.input :email_address, :label => false, :input_html => { :class => 'spa12' } %>
<% end %>
You need to be building/creating the contacts from the opening model, as opposed to trying to assign the contacts_attributes manually. Your controller code needs to look something like:
@opening.update_attributes(params[:opening])
Check out the Rails guide for more info on using nested attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With