Ruby on Rails:以表单提交数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3089849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: Submitting an array in a form
提问by William Jones
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?
我知道有一个带有名称包含括号的字段的表单输入会从输入中创建一个散列。我是否应该只是在控制器中执行它并逐步执行它以将其按摩到阵列中?
Example to make it less abstract:
使其不那么抽象的示例:
class Article
serialize :links, Array
end
The links variable takes the form of a an array of URLs, i.e. [["http://www.google.com"], ["http://stackoverflow.com"]]
links 变量采用 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" => ""}
If I don't include the url in the name of the link, additional values clobber each other:
如果我不在链接名称中包含 url,附加值会相互干扰:
<%= hidden_field_tag "article[links]", :track, :value => url %>
The result looks like this: "links" => "http://stackoverflow.com"
结果如下所示: "links" => "http://stackoverflow.com"
回答by Larry K
If your html form has input fields with empty square brackets, then they will be turned into an array inside params in the controller.
如果您的 html 表单具有带空方括号的输入字段,那么它们将在控制器中的 params 中转换为数组。
# 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
Added:
添加:
Note that the rails helpers are notsetup to do the array trick auto-magically. So you may have to create the nameattributes 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.
请注意,rails 助手没有设置为自动执行数组技巧。因此,您可能必须手动创建名称属性。此外,如果使用 rails 助手,复选框也有自己的问题,因为复选框助手会创建额外的隐藏字段来处理未选中的情况。
回答by stAndrei
= simple_form_for @article do |f|
= f.input_field :name, multiple: true
= f.input_field :name, multiple: true
= f.submit
回答by ecoologic
TL;DRversion of HTML []convention:
TL; DR版本的 HTML[]约定:
Array:
大批:
<input type="textbox" name="course[track_codes][]", value="a">
<input type="textbox" name="course[track_codes][]", value="b">
<input type="textbox" name="course[track_codes][]", value="c">
Params received:
收到的参数:
{ course: { track_codes: ['a', 'b', 'c'] } }
Hash
哈希
<input type="textbox" name="course[track_codes][x]", value="a">
<input type="textbox" name="course[track_codes][y]", value="b">
<input type="textbox" name="course[track_codes][z]", value="c">
Params received:
收到的参数:
{ course: { track_codes: { x: 'a', y: 'b', z: 'c' } }
回答by Ana Franco
I've also found out that if pass your input helper like this you will get an array of courses each one with its own attributes.
我还发现,如果像这样传递您的输入助手,您将获得一系列课程,每个课程都有自己的属性。
# Eg multiple input fields all with the same name:
<input type="textbox" name="course[][track_codes]" ...>
# will become the Array
params["course"]
# where you can get the values of all your attributes like this:
params["course"].each do |course|
course["track_codes"]
end
回答by Peter Ehrlich
I just set up a solution using jquery taginput:
我刚刚使用 jquery taginput 设置了一个解决方案:
http://xoxco.com/projects/code/tagsinput/
http://xoxco.com/projects/code/tagsinput/
I wrote a custom simple_form extension
我写了一个自定义的 simple_form 扩展
# for use with: http://xoxco.com/projects/code/tagsinput/
class TagInput < SimpleForm::Inputs::Base
def input
@builder.text_field(attribute_name, input_html_options.merge(value: object.value.join(',')))
end
end
A coffeescrpt snippet:
一个 coffeescrpt 片段:
$('input.tag').tagsInput()
And a tweak to my controller, which sadly has to be slightly specific:
还有对我的控制器的调整,遗憾的是必须稍微具体一点:
@user = User.find(params[:id])
attrs = params[:user]
if @user.some_field.is_a? Array
attrs[:some_field] = attrs[:some_field].split(',')
end
回答by sovanlandy
For those who use simple form, you may consider this solution. Basically need to set up your own input and use it as :array. Then you would need to handle input in your controller level.
对于那些使用简单表格的人,你可以考虑这个解决方案。基本上需要设置自己的输入并将其用作:array。然后您需要在控制器级别处理输入。
#inside lib/utitilies
class ArrayInput < SimpleForm::Inputs::Base
def input
@builder.text_field(attribute_name, input_html_options.merge!({value: object.premium_keyword.join(',')}))
end
end
#inside view/_form
...
= f.input :premium_keyword, as: :array, label: 'Premium Keyword (case insensitive, comma seperated)'
#inside controller
def update
pkw = params[:restaurant][:premium_keyword]
if pkw.present?
pkw = pkw.split(", ")
params[:restaurant][:premium_keyword] = pkw
end
if @restaurant.update_attributes(params[:restaurant])
redirect_to admin_city_restaurants_path, flash: { success: "You have successfully edited a restaurant"}
else
render :edit
end
end
In your case just change :premium_keyword to the your array field
在您的情况下,只需将 :premium_keyword 更改为您的数组字段

