Rails表单中的多个对象 [英] Multiple objects in a Rails form
本文介绍了Rails表单中的多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以一种形式编辑我的模特照片的多个项目。我不确定如何正确地呈现和POST这个表单,以及如何收集控制器中更新操作中的项目。
I want to edit multiple items of my model photo in one form. I am unsure of how to correctly present and POST this with a form, as well as how to gather the items in the update action in the controller.
这是我想要:
This is what I want:
<form>
<input name="photos[1][title]" value="Photo with id 1" />
<input name="photos[2][title]" value="Photo with id 2" />
<input name="photos[3][title]" value="Custom title" />
</form>
参数仅仅是一个例子,就像我上面所说的:我不确定最好的方法以这种形式发布这些值。
The parameters are just an example, like I stated above: I am not sure of the best way to POST these values in this form.
在控制器中,我想要这样的东西:
In the controller I want to something like this:
@photos = Photo.find( params[photos] )
@photos.each do |photo|
photo.update_attributes!(params[:photos][photo] )
end
推荐答案
在Rails 4中,只有这个
In Rails 4, just this
<%= form_tag photos_update_path do %>
<% @photos.each do |photo| %>
<%= fields_for "photos[]", photo do |pf| %>
<%= pf.text_field :caption %>
... other photo fields
这篇关于Rails表单中的多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文