复杂表单嵌套在Rails中 - 如何创建所需的哈希/数组参数输出

时间:2012-02-23 13:44:47

标签: ruby-on-rails ruby-on-rails-3 forms nested-forms simple-form

我试图找出如何正确处理params散列,以便我不会传递应该嵌套多次的params。

这是我的html.slim代码的简化(删除不需要的信息,如标签等)(使用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][]"}

好吧这个输入1个房间,1个成人,1个5岁的孩子我们得到这样的参数:

"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>["1", "0"]}, "children"=>{"1"=>{"ages"=>["5", ""]}, "2"=>{"ages"=>["", ""]}}

我真正想要的是params:

"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>["1"=>["5",""], "0"=>["",""]] }

任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

抱歉,我不知道simple_form是如何运作的,但是我会用普通的rails帮助程序来做这件事。

<%= 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 %>

这不会为您提供所需的确切输入,但它会为您提供类似

的内容
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>{"0"=>{child_age => ["5",""]}, "1"=>{child_age => ["",""]}}}

或者,如果您没有持久化对象,则应该可以使用

<%= 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 %>