【问题标题】:Rails access form parameter that is an arrayRails 访问表单参数,它是一个数组
【发布时间】:2016-06-14 15:11:27
【问题描述】:

我有一个允许输入多个 ID 的表单,例如:

<input name="the_ids[]"  type="text" placeholder="Enter an ID" />
<input name="the_ids[]"  type="text" placeholder="Enter an ID" />
<input name="the_ids[]"  type="text" placeholder="Enter an ID" />

当表单提交时,我得到的参数被传递为:

"the_ids"=>["1, 2, 3"],

在控制器中,我试图以如下方式访问它们:

params[:the_ids[]].each do |id|
  do_something_with(id)
end

我不断收到错误:

wrong number of arguments (0 for 1..2)
> params[:the_ids[]].each do |id|

跟踪显示如下:

app/controllers/the_controller.rb:10:in `[]'  

我想不通。我查看了其他一些帖子,并尝试使用其他语法访问,例如:

params["the_ids[]"]

但这产生了一个错误,说明它是一个 nil 类...

如果需要更多详细信息,请告知。

【问题讨论】:

    标签: ruby-on-rails arrays forms


    【解决方案1】:

    正如您在"the_ids"=&gt;["1, 2, 3"] 中看到的,参数名称为the_ids,您可以使用params[:the_ids] 访问它。

    params[:the_ids].each do |id|
      do_something_with(id)
    end
    

    name="the_ids[]" 中使用the_ids[] 只需要在客户端告诉Rails the_ids 将作为数组参数读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 2014-03-01
      相关资源
      最近更新 更多