如何在Rails 3.1中以单个forms创建多个对象?

我有一个Photo模型,我想设置一个表单,以便用户可以从同一个表单创建多个照片。 我在嵌套模型表单上观看了Railscast#196和197,但这比我需要的更复杂,并且更多地处理包含多个模型的表单,而不是同一模型的多个对象。 下面是我的一个简单表单的代码,它允许用户附加图像并创建一个新的Photo对象。 我已经尝试过fields_for并尝试嵌套,但它似乎过于复杂,我无法让它工作。 有关如何设置此表单以允许用户附加5个图像以创建5个新Photo对象的任何想法?

 { :class => "form-stacked", :multipart => "true" } ) do |f| %> 
"btn primary" %>

我最终使用plupload用于使用carrierwave上传多个文件(照片)。 我使用了plupload-rails gem和以下代码,一切运行良好:

 <%= javascript_tag do %> $(function(){ var uploader = $('#uploader').pluploadQueue({ runtimes : "html5, gears,flash,silverlight,browserplus", max_image_size : '100mb', url : "/photos", unique_names : true, multipart: true, preinit: attachCallbacks, multipart_params: { "authenticity_token" : '<%= form_authenticity_token %>' }, flash_swf_url : '/plupload/js/plupload.flash.swf', silverlight_xap_url : '/plupload/js/plupload.silverlight.xap' }); //end initial script //redirect after complete function attachCallbacks(uploader) { uploader.bind('FileUploaded', function(Up, File, Response) { if((uploader.total.uploaded + 1) == uploader.files.length){ var filesAdded = uploader.files.length; window.location = "<%=j edit_individual_photos_path %>"+ '?files=' + filesAdded; } }); } }); //end function <% end %> 

希望这有助于某人开始。

我喜欢Ryan Bates Nested_Form的gem,因为我很懒。 但我会这样做

 <%= semantic_nested_form_for @user, :html => {:multipart => true} do |f| %> <%= f.fields_for :photo %> 

<%= f.link_to_add "Add Photo", :photo %>

<%= f.submit :class => "btn-success" %>
<% end %>

然后是_photo.erb偏

 
<%= f.file_field :image %>

关于你的评论:

我想这就是你要找的东西,我在这里为你做了(基于Railscast载波集节目):

https://github.com/rbirnie/image-upload

基本来源:

画廊模型

 class Gallery < ActiveRecord::Base attr_accessible :name, :paintings_attributes has_many :paintings accepts_nested_attributes_for :paintings end 

绘画模型:

 class Painting < ActiveRecord::Base attr_accessible :gallery_id, :name, :image, :remote_image_url belongs_to :gallery mount_uploader :image, ImageUploader end 

画廊编辑

 <%= nested_form_for @gallery, :html => {:multipart => true} do |f| %> <%= f.error_messages %> 

<%= f.label :name %>
<%= f.text_field :name %>

<%= f.fields_for :paintings do |photo_form| %> <%= photo_form.label :name %> <%= photo_form.text_field :name %> <%= photo_form.file_field :image %> <%= photo_form.link_to_remove "Remove this photo" %> <% end %>

<%= f.link_to_add "Add a photo", :paintings %>

<%= f.submit %>

<% end %>