嵌套散列中的 Form_tag 参数 [英] Form_tag parameters in nested hash

查看:37
本文介绍了嵌套散列中的 Form_tag 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有关联模型的表单,所以我使用的是 form_tag 而不是 form_for.正如预期的那样,当用户提交表单时,每个字段都包含在 params 哈希中.但是表单会发生很大变化,我更希望在 params 哈希中包含一个哈希,以保存所有表单字段值,这样我就不必每次更改表单时都更改控制器.

I have a form that doesn't have a model associated with it, so I'm using form_tag rather than form_for. As expected, when the user submits the form each of the fields is included in the params hash. But the form will change a lot and I would prefer to have a hash within the params hash that will hold all of the form field values so that I don't have to change my controller every time I change my form.

有没有办法像 form_for 那样将表单字段值放入嵌套散列中?我希望能够通过执行诸如 params[:form_fields].to_json

Is there a way to put the form field values into a nested hash like form_for does? I'd like to be able to take all of the form fields and convert them to json by doing something like params[:form_fields].to_json

推荐答案

您可以使用 fields_for 位于 form_tag 中,用于表达命名空间的更正式方式.

You can use fields_for inside a form_tag for a more formal way of expressing a namespace.

fields_for :form_fields do |ff|
  ff.text_field :my_text_field
  ff.select :my_select_tag
end

或者只是命名所有表单输入,例如:

Alternatively just namespace all your form inputs, as such:

text_field_tag "form_fields[my_text_field]"
select_tag "form_fields[my_select_tag]" ...

等等.然后你会得到 params[:form_fields] = {:my_text_field =>"foo", :my_select_tag =>bar"},我认为这是您想要的.

etc. Then you will get params[:form_fields] = {:my_text_field => "foo", :my_select_tag => "bar"}, which I think is what you wanted.

这篇关于嵌套散列中的 Form_tag 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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