Ruby on Rails的:在一个表单提交一个数组 [英] Ruby on Rails: Submitting an array in a form
问题描述
我有了这是一个数组属性的模型。什么是对我来说,从表单提交填充该属性?有道
I have a model that has an attribute that is an Array. What's the proper way for me to populate that attribute from a form submission?
我知道有一个字段的名字包括括号创建一个从输入的散列的形式输入。我是不是应该是采取这一并通过它在控制器迈向按摩到一个数组中?
I know having a form input with a field whose name includes brackets creates a hash from the input. Should I just be taking that and stepping through it in the controller to massage it into an array?
为例,以减少摘要:
class Article
serialize :links, Array
end
的链接变量采用的形式的URL的数组,即 [http://www.google.com],[http://stackoverflow.com]]
当我使用的东西,像我的形式下,它会创建一个哈希:
When I use something like the following in my form, it creates a hash:
<%= hidden_field_tag "article[links][#{url}]", :track, :value => nil %>
得到的哈希值是这样的:
The resultant hash looks like this:
"links" => {"http://www.google.com" => "", "http://stackoverflow.com" => ""}
如果我不包括在链接的名称的URL,附加值揍对方:
If I don't include the url in the name of the link, additional values clobber each other:
<%= hidden_field_tag "article[links]", :track, :value => url %>
结果是这样的:链接=&GT; http://stackoverflow.com
推荐答案
如果你的HTML表单与空方括号中输入字段,那么他们将会变成内部控制器PARAMS的数组。
If your html form has input fields with empty square brackets, then they will be turned into an array inside params in the controller.
# Eg multiple input fields all with the same name:
<input type="textbox" name="course[track_codes][]" ...>
# will become the Array
params["course"]["track_codes"]
# with an element for each of the input fields with the same name
补充:
请注意,该导轨佣工是的不的设置做阵列伎俩自动神奇。所以,你可能需要创建的名称的手动属性。此外,由于该复选框助手创建额外的隐藏字段来处理未选中复选框的情况下有自己的问题,如果使用导轨佣工。
Note that the rails helpers are not setup to do the array trick auto-magically. So you may have to create the name attributes manually. Also, checkboxes have their own issues if using the rails helpers since the checkbox helpers create additional hidden fields to handle the unchecked case.
这篇关于Ruby on Rails的:在一个表单提交一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!