Post Rails 中的多个输入字段作为列表而不是单独的名称。

Post multiple input fields in Rails as a List instead of with individual names.

我想用 form_for 向控制器提交一个列表。此列表应填充 text_fields.

此实现将提交 :some_list,列表中只有一个 text_field 的值(如预期)。我希望将 X 数量的 text_field 作为列表提交,因为文本字段的数量是动态的,以接收类似的东西:params {..."name":"Something", "some_list":["a", "b"]} 或一些 JSON 等价物。


.erb

<%= form_for @my_model do |f|%>
  <% f.text_field :name %>

  <% (0...@some_limit).each do |index| %>
    <%= f.text_field :some_list %>
  <% end %>
<% end %>


模特

注意模型不是 ActiveRecord

class MyModel

  include ActiveModel::Model
  include ActiveModel::Validations

  attr_accessor :name, :some_list

  validates :name, :presence => true
  validates :some_list, :presence => true

end

用 text_field 名字添加 multiple: true

<%= form_for @my_model do |f|%>
  <% f.text_field :name %>

  <% (0...@some_limit).each do |index| %>
    <%= f.text_field :some_list, multiple: true %>
  <% end %>
<% end %>

你可以这样使用text_field_tag,

<% (0...@some_limit).each do |index| %>
  <%= text_field_tag "#{f.object.class.to_s.underscore}[some_list][]" %>
<% end %>

这是一种 hack,接受的答案是适当的解决方案。