问题
I'm trying to figure out how to properly handle the params hash so as I dont pass params that should be nested multiple times..
Here is a simplified(removed not-needed info like labels etc) of my html.slim code (using simple_form):
= f.simple_fields_for :room do |r|
- (1..4).each do |room|
= r.input 'adults',:collection => 1..4,:input_html => {:name => "room[adults][]"}
= r.input 'children',:collection => 0..2,:input_html => {:name => "room[children][]"}
- (1..2).each do |child|
= r.input 'child_age',:input_html => {:name => "children[#{child}][ages][]"}
ok this with inputs of 1 room, 1 adult,1 child of age 5 we get params like this :
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>["1", "0"]}, "children"=>{"1"=>{"ages"=>["5", ""]}, "2"=>{"ages"=>["", ""]}}
what I actually want to have on params is this:
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>["1"=>["5",""], "0"=>["",""]] }
anyone got any idea on how to do that?
回答1:
Sorry, I don't know how simple_form
works, but here's how I would do it in with normal rails
helpers.
<%= f.fields_for :rooms, (rooms_collection) do |r| %>
... # Any inputs you may want
<%= r.fields_for :children, (children_collection) do |c| %>
<%= c.text_field :child_age %>
This won't give you the exact input you want but it will give you something like
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>{"0"=>{child_age => ["5",""]}, "1"=>{child_age => ["",""]}}}
Alternatively if you don't have persisted objects this should work
<%= f.fields_for :rooms do |r| %>
... # Any inputs you may want
(1..2).each do
<%= r.fields_for :children do |c| %>
<%= c.text_field :child_age %>
来源:https://stackoverflow.com/questions/9414261/complex-form-nesting-in-rails-how-to-create-the-desired-hash-array-params-ou