如何从 Rails 中的同一页面提交多个重复的表单 - 最好使用一个按钮
在我的新视图页面中,我有:
<% 10.times do %>
<%= render 'group_member_form' %>
<% end %>
现在此表单包含字段:first_name
、last_name
、email_address
和 mobile_number
。基本上,我希望能够一键填写所有表单的字段,然后将每个表单作为唯一的行/id 提交到数据库中。
实现这一目标最简单的方法是什么?
注意:从变量调用 do 的次数。欢迎任何建议,谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该只有一个表单(您应该只在
group_member_form
部分中放置字段)。在您看来,您应该有类似的内容:在
_group_member_form.html.erb
中您应该有这样的方式,当表单提交时,控制器中的
params[:members]
将是成员哈希的数组。因此,例如,要在提交表单后从第四个成员那里获取电子邮件地址,您可以调用params[:members][3][:email_adress]
。要理解为什么我这样写
_group_member_form.html.erb
,请看一下:http://guides.rubyonrails.org/form_helpers.html#understanding-parameter-naming-conventions。
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:and in
_group_member_form.html.erb
you should haveThis 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 callparams[: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.
您还可以在模型中使用accepts_nested_attributes_for,并在表单上使用fields_for。
提交多个表单,据我所知,只有 javascript,如果表单是远程的:true,并且您运行每个表单然后提交。
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_with 和 fields_for 的更新方法,无需将表单删除为部分,可以如下编写:
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: