Ruby on Rails:提交表单中的数组

时间:2010-06-22 02:26:11

标签: ruby-on-rails arrays forms hash

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

我知道有一个带有字段的表单输入,其名称包括括号,从输入创建一个哈希。我应该只是拿着它并在控制器中踩过它来按摩它成阵列吗?

使其不那么抽象的例子:

class Article
  serialize :links, Array
end

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

当我在表单中使用类似下面的内容时,它会创建一个哈希:

<%= hidden_field_tag "article[links][#{url}]", :track, :value => nil %>

结果哈希看起来像这样:

"links" => {"http://www.google.com" => "", "http://stackoverflow.com" => ""}

如果我没有在链接名称中包含网址,则其他值会相互冲突:

<%= hidden_field_tag "article[links]", :track, :value => url %>

结果如下所示:"links" => "http://stackoverflow.com"

7 个答案:

答案 0 :(得分:87)

如果你的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

添加了:

请注意,rails帮助程序设置为自动神奇地执行数组技巧。因此,您可能必须手动创建名称属性。此外,如果使用rails助手,复选框也有自己的问题,因为复选框助手会创建其他隐藏字段来处理未经检查的案例。

答案 1 :(得分:46)

= simple_form_for @article do |f|
  = f.input_field :name, multiple: true
  = f.input_field :name, multiple: true
  = f.submit

答案 2 :(得分:38)

TL; DR 版本的HTML []约定:

阵列:

<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收到:

{ course: { track_codes: ['a', 'b', 'c'] } }

哈希

<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收到:

{ course: { track_codes: { x: 'a', y: 'b', z: 'c' } }

答案 3 :(得分:8)

我还发现,如果像这样传递你的输入助手,你会得到一系列课程,每个课程都有自己的属性。

# 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    

答案 4 :(得分:7)

我只是使用jquery taginput设置解决方案:

http://xoxco.com/projects/code/tagsinput/

我写了一个自定义的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

coffeescrpt片段:

$('input.tag').tagsInput()

对我的控制器进行调整,遗憾的是必须稍微具体一点:

@user = User.find(params[:id])
attrs = params[:user]

if @user.some_field.is_a? Array
  attrs[:some_field] = attrs[:some_field].split(',')
end

答案 5 :(得分:1)

我有一个类似的问题,但是想让用户输入一系列用逗号分隔的元素作为数组的值。 我的迁移使用Rails的新功能(或者是postrges的新功能?)将数组作为列类型

add_column :articles, :links, :string, array: true, default: []

然后表格可以接受此输入

<%= text_field_tag "article[links][]", @article.links %>

这意味着控制器可以按照以下方式非常平稳地运行

def create
  split_links
  Article.create(article_params)
end

private
def split_links
  params[:article][:links] = params[:article][:links].first.split(",").map(&:strip)
end


params.require(:article).permit(links: [])

现在,用户可以输入任意数量的链接,并且表单在创建和更新时均行为正常。而且我仍然可以使用强大的参数。

答案 6 :(得分:0)

对于那些使用简单表单的人,您可以考虑这个解决方案。基本上需要设置自己的输入并将其用作:数组。然后,您需要在控制器级别处理输入。

#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

在您的情况下,只需将premium_keyword更改为您的数组字段