Ruby on Rails:以表单提交数组 [英] Ruby on Rails: Submitting an array in a form

查看:48
本文介绍了Ruby on Rails:以表单提交数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有数组属性的模型.我从表单提交中填充该属性的正确方法是什么?

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

links 变量采用 URL 数组的形式,即 [["http://www.google.com"], ["http://stackoverflow.com"]]

The links variable takes the form of a an array of URLs, i.e. [["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 %>

结果散列如下所示:

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

结果如下:"links" =>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

添加:

请注意,rails 助手没有设置为自动执行数组技巧.因此,您可能必须手动创建 name 属性.此外,如果使用 rails 助手,复选框也有自己的问题,因为复选框助手会创建额外的隐藏字段来处理未选中的情况.

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屋!

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