Search code examples
ruby-on-railsruby-on-rails-4erbform-for

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


I would like to submit a list to the controller with a form_for. This list should be populated with text_fields.

This implementation will submit :some_list with the value of only one text_field in the list (as expected). I want X amount of text_fields to be submitted as a list, since the number of text fields is dynamic, as to receive something of the sort: params {..."name":"Something", "some_list":["a", "b"]} or some JSON equivalent.


.erb

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

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


The Model

Note the Model is not an ActiveRecord

class MyModel

  include ActiveModel::Model
  include ActiveModel::Validations

  attr_accessor :name, :some_list

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

end

Solution

  • Add multiple: true with text_field name.

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