Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit multiple, duplicate forms from same page in Rails - preferably with one button

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!

like image 797
user1224344 Avatar asked Feb 22 '12 13:02

user1224344


1 Answers

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.

like image 59
janko-m Avatar answered Oct 04 '22 22:10

janko-m