0

Im trying to create inputs by looping each product and have one form submission for all the inputs. Currently, the form only submits the last input. How would I make it so all the inputs get submitted?

<%= form_for :inventory do |f| %>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= product.measurement %></td>
        <td><%= f.number_field :amount, class: 'form-control' %></td>
        <%= f.hidden_field :product_id, :value => product.id %>
      </tr>
      <% end %>
     <%= f.submit %>
<% end %>
Marco G
  • 11
  • 7
  • Possible duplicate of [Multiple objects in a Rails form](https://stackoverflow.com/questions/972857/multiple-objects-in-a-rails-form) – ragurney May 15 '18 at 16:35
  • 1
    You need to make the hidden field unique for each iteration. Here generated hidden field has same id which returns last value as other values get override.. – APS May 15 '18 at 16:57

2 Answers2

0

I dont know your use case but you can use the gem cocoon for doing that. There will also be a link to add/remove another product.

https://github.com/nathanvda/cocoon

0

You can iterate with each_with_index:

<%= form_for :inventory do |f| %>
  <% @products.each_with_index do |product, i| %>
    <tr>
      <%= f.hidden_field "product_id[#{i}]", :value => product.id %>
    </tr>
    <% end %>
  <%= f.submit %>
<% end %>

Like that the output is not very elegant (something like "product_id"=>{"0"=>"1", "1"=>"2", "2"=>"3"... }) but it's for the example to show how every hidden field needs a unique key.
You can define your params in a better way to use them in the controller, just keep them unique.

Sovalina
  • 5,410
  • 4
  • 22
  • 39