我有一个Photo模型,我想设置一个表单,以便用户可以从同一个表单创建多个照片。我在嵌套模型表单上观看了Railscast#196和197,但这比我需要的更复杂,并且更多地处理包含多个模型的表单,而不是同一模型的多个对象。下面是我的一个简单表单的代码,它允许用户附加图像并创建一个新的Photo对象。我已经尝试过fields_for并尝试嵌套,但它似乎过于复杂,我无法让它工作。关于如何设置此表单的任何想法允许用户附加5个图像以创建5个新的Photo对象?
<%= 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 %>
答案 0 :(得分:1)
我最终使用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 %>
<div class="" id="uploader"></div>
希望这有助于某人开始。
答案 1 :(得分:0)
我喜欢Ryan Bates Nested_Form的宝石,因为我很懒。但我会这样做
<%= semantic_nested_form_for @user, :html => {:multipart => true} do |f| %>
<%= f.fields_for :photo %>
<p><%= f.link_to_add "Add Photo", :photo %></p>
<div class="actions">
<%= f.submit :class => "btn-success" %>
</div>
<% end %>
然后是_photo.erb部分
<div class="clearfix">
<%= f.file_field :image %>
</div>
关于你的评论:
我认为这就是你要找的东西,我在这里为你做了(基于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 %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<%= 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 %>
<p><%= f.link_to_add "Add a photo", :paintings %></p>
<p><%= f.submit %></p>
<% end %>
〜