我已经在 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/