Create a new entry in the Rails HABTM nested form

I have a nested form (using Ryan B nested_form gem) using has_and_belongs_to_many to set has_and_belongs_to_many:

Opening has_and_belongs_to_many :contacts

Contact has_and_belongs_to_many :openings

When I try to add a new contact to the 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 added the appropriate "accepts_nested_attributes_for" and "attr_accessible" and create a contact, that is, @ opening.contacts.build and @ opening.contacts.build (params [: opening] [: contact_attributes]) in the controller.

Where am I mistaken? Would it be better to use has_many through the relationships here?

EDIT:

View:

<%= simple_nested_form_for @opening, :wrapper => :plain do |f| %>
  <%= f.link_to_add "Add a contact", :contacts %>
  <%= f.button :submit %>
<% end %>

Uses the partial creation of fields for a 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 %>
+5
source share
1 answer

/ , contacts_attributes. :

@opening.update_attributes(params[:opening])

Rails guide

+2

All Articles