A Rails form with multiple nested models causes problems with radio groups

I have a problem with nested model forms that contain switches, when I have several models, all radio buttons are considered to be in the same group.

My model contains has_many relationships as follows:

class Order < ActiveRecord::Base
    has_many :order_items
    accepts_nested_attributes_for :order_items
end

Class OrderItem < ActiveRecord::Base
    belongs_to :order
end

Then I have a partial one that creates a model model OrderItemusing

<% fields_for "order[order_items_attributes][]", order_item do |f| %>

And contained in this form is a group of switches created inside a for loop with

radio_button_tag "order[order_items_attributes][][colour_id]", "#{colour.id}"

, , , , , name="order[order_items_attributes][][colour_id]". , (name="order[order_items_attributes][0][colour_id]"), Rails expected Hash (got Array) for param 'order_items_attributes' , , , .

params[:order], :

{"order_items_attributes"=>
  [{"size"=>"Small",
    "colour_id"=>"4"],
 "first_name"=>"sdf",
 "last_name"=>"sdf",
 "email"=>"sdfg@sgf.com"}

:

{"order_items_attributes"=>
  [{"size"=>"Small",
    "colour_id"=>"4"},
   {"size"=>"Small"}],
 "first_name"=>"sdf",
 "last_name"=>"sdf",
 "email"=>"sdfg@sgf.com"}

, order_item colour_id. , ( ).

, ?

+5
1

, . fields_for , , fields_for. Rails , .

.

<%form_for :order do |f|%>
  Form stuff for this particular order.
  If @order.order_items is empty you may need to build one before the next line.
  <%f.fields_for :order_items do |oi_f| %>
    Form stuff for this particular order_item (prefixed with oi_f.)
    <%Colour.all.each do |colour| %>
      <%=oi_f.radio_tag(:colour_id, colour.id)%>
    <%end%>
  <%end%>
<%end%>

, order_controller, .

+3

All Articles