使用Paperclip将对象关联到S3上的预先存在的文件

Sim*_*kin 5 ruby-on-rails amazon-s3 paperclip ruby-on-rails-3 fog

我已经在S3上有一个文件,我想将其关联到预先存在的Asset模型实例.

这是模型:

class Asset < ActiveRecord::Base
  attr_accessible(:attachment_content_type, :attachment_file_name,
                 :attachment_file_size, :attachment_updated_at, :attachment)

  has_attached_file :attachment, {
    storage: :s3,
    s3_credentials: {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    },
    convert_options: { all: '-auto-orient' },
    url: ':s3_alias_url',
    s3_host_alias: ENV['S3_HOST_ALIAS'],
    path: ":class/:attachment/:id_partition/:style/:filename",
    bucket: ENV['S3_BUCKET_NAME'],
    s3_protocol: 'https'
  }
end
Run Code Online (Sandbox Code Playgroud)

假设路径是assets/attachments/000/111/file.png,并且Asset我想要与文件关联的实例是asset.在消息来源,我试过:

options = {
    storage: :s3,
    s3_credentials: {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    },
    convert_options: { all: '-auto-orient' },
    url: ':s3_alias_url',
    s3_host_alias: ENV['S3_HOST_ALIAS'],
    path: "assets/attachments/000/111/file.png",
    bucket: ENV['S3_BUCKET_NAME'],
    s3_protocol: 'https'
  }
# The above is identical to the options given in the model, except for the path

Paperclip::Attachment.new("file.png", asset, options).save
Run Code Online (Sandbox Code Playgroud)

据我所知,这并没有asset任何影响.我不能asset.attachment.path手动设置.

关于SO的其他问题似乎没有具体解决这个问题." 回形针图像没有保存在我设置的路径中 "," Paperclip和Amazon S3如何做路径? "等等涉及设置模型,该模型已经正常工作.

有人有任何洞察力吗?

Sim*_*kin 3

据我所知,我确实需要将 S3 对象转换为File,正如 @oregontrail256 所建议的。我使用宝石来做到这一点。

s3 = Fog::Storage.new(
        :provider => 'AWS',
        :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
        :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
      )

directory = s3.directories.get(ENV['S3_BUCKET_NAME'])
fog_file = directory.files.get(path)

file = File.open("temp", "wb")
file.write(fog_file.body)
asset.attachment = file
asset.save
file.close
Run Code Online (Sandbox Code Playgroud)