Rails使用s3_file_field嵌套多文件上传到amazon s3

时间:2014-08-19 04:01:35

标签: ruby-on-rails ruby amazon-s3 filefield

我一直试图在rails中的嵌套模型上进行多图像上传。我一直在使用s3_file_field宝石,可以找到here

我已经创建了一个要点,其中显示了我的代码的相关部分here

当我尝试上传两个图像时,两个图像都上传到S3,但只有一个Image对象保存到数据库中。我需要找到一种方法来为每个上传到S3的图像创建一个Image对象。

1 个答案:

答案 0 :(得分:0)

我提出了类似的问题here ....使用paperclip >= 4s3来完成这项工作。

class Image < ActiveRecord::Base
  has_many :image_photos , :dependent => :destroy
  accepts_nested_attributes_for :image_photos, :reject_if => lambda { |a| a[:avatar].blank? }, :allow_destroy => true
end


class ImagePhoto < ActiveRecord::Base
 belongs_to :image
 has_attached_file :avatar,
  :styles => {:view => "187x260#"},
  :storage => :s3,
  :s3_permissions => :private,
  :s3_credentials => S3_CREDENTIALS
 attr_accessible :image_id,:avatar,:avatar_file_name,:avatar_content_type,:avatar_file_size,:avatar_updated_at
 validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
 validates_presence_of :avatar
end
控制器中的

 def new
if current_or_guest_user.pic_categories.present?
 @image = Image.new
 #3.times {@image.image_assets.build} # added this
 @image.image_photos.build

end 

 def create
@image = Image.new(params[:image])
@image.user_id = current_or_guest_user.id
 if @image.save
   if params[:image_photos][:avatar]
     params[:image_photos][:avatar].each { |image|
       @image.image_photos.create(avatar: image)
       }
      end
@image.create_activity key: 'image.create', owner: current_or_guest_user
end

<强> _form.html.erb

<%= form_for(@image,:html=>{:multipart => true,:remote=>true,:class=>"form-horizontal",:role=>"form"}) do |f |%>
 <%= f.fields_for :image_photos do |builder| %>
<% if builder.object.new_record? %>
   Upload picture
  <!-- to add multiple images--> 
  <%= builder.file_field :avatar,:multiple=>"true",:name=>"image_photos[avatar]  []",:class=>"opacity"%></a>
 <%end%>


<%end%>