Rails form with multiple nested models causes issues with radio groups -
I am having problems with nested models, which have radio buttons, when I have many models, then all the radios Button is behaved as it is in the same group.
In my model there is one more relationship like this:
class command & lt; ActiveRecord :: Base is -Media: order_items accepts_cent_data_paign: order_items end class order item & lt; ActiveRecord :: Base is_to: order end
Then I have partial by using OrderItem
model form
& lt ; For% Fields_ "order [order_times_entaries] []", order_item do | F | & Gt%;
and there is a group of radio buttons contained in this form that
radio_button_tag "order [order_items_attributes] [] [color_id]" with loop Designed for , "# {Color.id}"
It works fine only when there is only one child, but as soon as I incorporate many children, all the radio buttons The same feature related to the same group is name = "order [order_items_attributes] [] [color_id]"
. This is all new model on the form so I can not use the array index ( name = "order [order_items_attributes] [0] [color_id]"
) because the rail error is expected (the absolute hash 'Order_times_tribbutes' is found)
I was wrong about that last part, the error was because I was getting the indexed and non-indexed name attributes, adding the index value was the key to solving it.
Here is the content of the parameters: [order]
hash only exists when a nested model is present:
{"order_items_attributes "= & Gt; [{"Size" = & gt; "Small", "color_id" => "4"], "first_name" = & gt; "Sdf", "last_name" = & gt; "Sdf", "email" = & gt; "Sdfg@sgf.com"}
and when two nested models are present:
{"order_items_attributes" => ["Size" = & gt; "Small", "color_id" => "4"}, {"size" = & gt; "Small"}], "first_name" = & gt; "Sdf", "last_name" = & gt; "SDF", "e-mail" = & gt; "Sdfg@sgf.com"}
As you can see only the first order_item
, this is the color_id attribute. This happens even as there is no model of selected radio button (which makes sense).
How can I present a radio button such that each child creates a separate group for the model?
When you call fields_, you will see each order item with a unique index If you are calling field_ this way, you need to keep track of the orange indicator to be passed for field_. Rails can do this for you using nested forms.
The solution is to use nested forms.
& lt;% form_for: order do | F |% & gt; Form form for this special order. If @ order.order_items is empty, then you may need to create one before the next line & lt;% f.fields_for: order_items do | Oi_f | & Gt%; Form content for this particular order_item (prefixed with oi_f.) <% Color.all.each do | Color | & Gt%; & Lt;% = oi_f.radio_tag (: color_id, color.id)%> & Lt;% end% & gt; & Lt;% end% & gt; & Lt;% end% & gt;
It seems that you are posting on the order_controller, so it should be a drop in the replacement.
Comments
Post a Comment