Rails fields_for parameters for a has_many relation don't yield an Array in params

Posted by user1289061 on Stack Overflow See other posts from Stack Overflow or by user1289061
Published on 2012-03-23T20:19:23Z Indexed on 2012/03/31 23:30 UTC
Read the original article Hit count: 344

Filed under:
|

I have a model Sensor with has_many and accepts_nested_attributes_for relationships to another model Watch. In a form to update a Sensor, I have something like the following

<%= sensor_form.fields_for :watches do |watches_form| %>
   <%= watches_form.label :label %><br />
   <%= watches_form.text_field :label %>
<% end %>

This is indended to allow editting of the already-created Watches belonging to a Sensor.

This call spits form inputs as so:

<input name="sensor[watches_attributes][0][label]" ... />
<input name="sensor[watches_attributes][0][id]" ... />

When this gets submitted, the params object in the Sensor controller gets an assoc like

"sensor" => {
  "id"=>"1",
   "watches_attributes"=> { 
     "0"=>{"id" => "1", "label" => "foo"},
     "1"=>{"id" => "2", "label" => "bar"}
   }
}

For a has_many, accepts_nested_attributes_for update to work upon the @sensor.update_attributes call, it seems that that attributes key really must map to an Array.

From what I've seen in the examples, the combination of has_many, accepts_nested_attributes_for, and sensor_form.fields_for should allow me to pass the resulting params object directly to @sensor.update_attributes and update each related object as intended. Instead the Sensor takes place, with no errors, but the Watch objects are not updated (since "watches_attributes" maps to a Hash instead of an Array?) Have I missed something?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about has-many