如何从 Rails 中的同一页面提交多个重复的表单 - 最好使用一个按钮
在我的新视图页面中,我有:
In my new views page I have:
<% 10.times do %>
<%= render 'group_member_form' %>
<% end %>
现在此表单包含以下字段:first_name
、last_name
、email_address
和 mobile_number
.基本上,我希望能够一键填写所有表单的字段,然后将每个表单作为唯一的行/id 提交到数据库中.
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?
注意:从变量调用 do 的次数.欢迎任何建议,谢谢!
Note: The number of times do is called from a variable. Any advice welcome, thanks!
你应该只有一个表单(你应该只在 group_member_form
部分中放置字段).在您看来,您应该具有以下内容:
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 %>
在_group_member_form.html.erb
中你应该有
<%= text_field_tag "members[][first_name]" %>
<%= text_field_tag "members[][last_name]" %>
<%= text_field_tag "members[][email_address]" %>
<%= text_field_tag "members[][mobile_number]" %>
这样,当表单提交时,控制器中的 params[:members]
将是一个成员哈希数组.因此,例如,要在提交表单后从第四个成员那里获取电子邮件地址,请调用 params[:members][3][:email_adress]
.
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]
.
要理解我为什么这样写_group_member_form.html.erb
,请看一下:
To understand why I wrote _group_member_form.html.erb
like this, take a glance at this: