Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new record in Rails HABTM nested form

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 %>
like image 926
Chris Edwards Avatar asked Nov 04 '22 16:11

Chris Edwards


1 Answers

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

like image 115
Peter Brown Avatar answered Nov 08 '22 07:11

Peter Brown