How to submit multiple duplicate forms from one page in Rails - preferably with a single button

On my new page views, I:

<% 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 forms with one click, which then sends each to the database as a unique string / id.

What would be the easiest way to do this?

Note. The number of times called from a variable. Any tips are welcome, thanks!

+4
source share
2 answers

You should have only one form (you should only place the fields in the group_member_form part). In your opinion, 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]" %> 

Thus, when the form is submitted, params[:members] in the controller will be an array of hashes of the elements. So, for example, to get the email address 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 as follows, take a look at this:

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

+12
source

You can also use accepts_nested_attributes_for in your model and use fields for your form.

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

 $("form.class_of_forms").each(function() { $(this).submit(); }); 
0
source

Source: https://habr.com/ru/post/1397813/


All Articles