5

In my new views page I have:

<% 10.times do %>
  <%= render 'group_member_form' %>     
<% end %>

Now this form contains the fields: first_name, last_name, email_address and mobile_number. Basically I want to be able to fill in the fields of all the forms in one click which then submits each into the database as a unique row/id.

What would be the easiest way to accomplish this?

Note: The number of times do is called from a variable. Any advice welcome, thanks!

DIF
  • 2,470
  • 6
  • 35
  • 49
user1224344
  • 129
  • 2
  • 11
  • preferably you would have some model, which has_many those models for which you have a form now, and use a fields_for method here – alony Feb 22 '12 at 15:22

3 Answers3

16

You should have only one form (you should put only fields in the group_member_form partial). In your view you should have something like:

<%= form_tag "/members" do %>
  <% 10.times do %>
    <%= render 'group_member_form' %>     
  <% end %>
  <%= submit_tag "Submit" %>
<% end %>

and in _group_member_form.html.erb you should have

<%= text_field_tag "members[][first_name]" %>
<%= text_field_tag "members[][last_name]" %>
<%= text_field_tag "members[][email_address]" %>
<%= text_field_tag "members[][mobile_number]" %>

This way, when the form submits, params[:members] in the controller will be an array of member hashes. So, for example, to get the email adress from the fourth member after submitting the form, you call params[:members][3][:email_adress].

To understand why I wrote _group_member_form.html.erb like this, take a glance at this:

http://guides.rubyonrails.org/form_helpers.html#understanding-parameter-naming-conventions.

Janko
  • 8,985
  • 7
  • 34
  • 51
  • Similar question: http://stackoverflow.com/questions/17775118/merge-two-forms-rails MAybe you can help me – Em Sta Jul 21 '13 at 17:58
0

Alternatively a more up to date approach using form_with and fields_for, without removing the form into a partial, could be written like this:

<%= form_with (url: end_point_path), remote: true do |form| %>
    <% (1..5).each do |i| %>
        <%= fields_for 'cart_items'+[i].to_s do |fields|%>
            <%= fields.text_field :first_name  %>
            <%= fields.text_field :last_name  %>
            <%= fields.email_field :email_address  %>
            <%= fields.number_field :phone_number %>
        <% end %>
    <% end %>
    <%= form.submit "Submit" %>
<% end %>
Victor
  • 35
  • 5
0

You can also use accepts_nested_attributes_for in your model, and use fields_for on your form.

Submitting multiple forms, afaik, only javascript, if the forms are remote: true, and you run through each of them and then submit.

$("form.class_of_forms").each(function() {
  $(this).submit();
});
berislavbabic
  • 459
  • 5
  • 9