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

标签 ruby-on-rails ruby-on-rails-3 amazon-s3 paperclip fog

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

这是模型:

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

假设路径是 assets/attachments/000/111/file.png ,以及 Asset我想与文件关联的实例是 asset .引用 source , 我试过了:
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

据我所知,这并没有影响 asset以任何方式。我无法设置 asset.attachment.path手动。

关于 SO 的其他问题似乎没有专门解决这个问题。
paperclip images not saving in the path i've set up ”、“Paperclip and Amazon S3 how to do paths? ”等涉及设置模型,该模型已经运行良好。

任何人都可以提供任何见解?

最佳答案

据我所知,我确实需要将 S3 对象变成 File ,正如@oregontrail256 所建议的那样。我用了 Fog gem 来做到这一点。

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

关于ruby-on-rails - 使用 Paperclip 将对象关联到 S3 上预先存在的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23532692/

相关文章:

javascript - 在 angular2 中使用 http 访问 Amazon s3

ruby-on-rails - 未定义的方法 `link_to_remote' 在 MiniTest 中用于 application_helper 测试

ruby-on-rails - rails v2.3 : Difference between session and cookies

ruby-on-rails - 如何使用 googlecharts gem?

c# - 如何列出 Amazon S3 存储桶中的所有对象?

amazon-s3 - 如何通过 *.cloudfront.net url 禁用对云端的访问?

Ruby-on-rails 4 性能低下

ruby-on-rails - 设计:新错误(Encrytable)

ruby-on-rails - Rails 5 hasMany 通过是不是过滤

ruby-on-rails-3 - 在引用 super 之前,单表继承子类未知