【问题标题】:Rails nested multi file upload to amazon s3 using s3_file_fieldRails 使用 s3_file_field 将嵌套多文件上传到亚马逊 s3
【发布时间】:2014-10-12 02:04:18
【问题描述】:

我一直在尝试在 Rails 中的嵌套模型上上传多张图片。我一直在使用s3_file_field gem,可以找到here

我创建了一个要点,它显示了我的代码的相关部分,可在here 找到。

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

【问题讨论】:

  • 嵌套模型和表格让我畏缩不前。当您具有该级别的复杂性时,您可能应该创建一个新对象来处理它。尝试表单对象 - 在这里查看另一个答案:stackoverflow.com/a/25298020/1448966

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


【解决方案1】:

我提出了一个类似的问题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%>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 2013-06-09
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多