我如何在Rails 3.1中以单一形式创建多个对象? [英] How can I create multiple objects in a single form in Rails 3.1?
问题描述
我有一个照片模型,我想设置一个表格,以便用户可以从同一个表单创建多张照片。我在嵌套模型窗体上观看了Railscasts#196和197,但是这比我需要的更复杂,并且更多地处理包含多个模型的表单,而不是同一模型的多个对象。下面是我的一个简单的表单代码,它允许用户附加图像并创建一个新的Photo对象。我已经试过了fields_for并尝试了嵌套,但它看起来过于复杂,我无法正常工作。关于如何设置此表单以允许用户附加5张图片以创建5个新照片对象的任何想法?
I have a Photo model and I want to set up a form so that a user can create multiple photos from the same form. I've watched the Railscasts #196 and 197 on nested model forms but that is more complex than what I need and deals more with forms containing multiple models, not multiple objects of the same model. Below is my code for a simple form that lets a user attach an image and create a new Photo object. I've experimented with fields_for and tried nesting but it seems overly complicated and I can't get it working. Any ideas on how I could set this form up to allow the user to attach 5 images to create 5 new Photo objects?
<%= form_for(@photo, :html => { :class => "form-stacked", :multipart => "true" } ) do |f| %>
<div class="clearfix">
<%= f.file_field :image %>
</div>
<div><%= f.submit "Upload", :class => "btn primary" %></div>
<%end %>
推荐答案
我最终使用plupload为多个文件)用carrierwave上传。我使用了plupload-rails gem和以下代码,并且所有代码都很好:
I ended up using plupload for the multiple file (photo) uploads with carrierwave. I used the plupload-rails gem and the following code and all works well:
<%= 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 %>
<div class="" id="uploader"></div>
希望这有助于某人开始行动。
Hope this helps someone get going.
这篇关于我如何在Rails 3.1中以单一形式创建多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!