Rails中的复杂表格嵌套-如何创建所需的哈希/数组参数输出 [英] Complex Form Nesting in Rails - How to create the desired hash / array params output

查看:157
本文介绍了Rails中的复杂表格嵌套-如何创建所需的哈希/数组参数输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何正确处理params哈希值的方法,以免不传递应嵌套多次的params.

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..

这是我的html.slim代码的简化(删除了不需要的信息,例如标签等)(使用simple_form):

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][]"}

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

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?

推荐答案

对不起,我不知道simple_form的工作原理,但是这是我将如何使用普通的rails助手进行的工作.

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

这篇关于Rails中的复杂表格嵌套-如何创建所需的哈希/数组参数输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆