[英]Associate object to pre-existing file on S3, using Paperclip
我已经在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
假设路径为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
据我所知,这丝毫没有影响asset
。 我无法手动设置asset.attachment.path
。
关于SO的其他问题似乎并未专门解决。 “ 无法在我设置的路径中保存回形针图像 ”,“ Paperclip和Amazon S3如何执行路径? ”,等等,包括建立模型,这已经可以正常工作了。
有人有什么见识吗?
据我所知, 确实需要按照@ oregontrail256的建议将S3对象转换为File
。 我使用了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
回形针附件具有copy_to_local_file()方法,该方法使您可以创建附件的本地副本。 那么呢:
file_name = "temp_file"
asset1.attachment.copy_to_local_file(:style, file_name)
file = File.open(file_name)
asset2.attachment = file
file.close
asset2.save!
即使销毁asset1,您现在也拥有资产2单独保存的附件的副本。 如果您要执行许多操作,则可能需要在后台执行此操作。
也要相信这个答案: 如何使用Paperclip以编程方式设置文件上传
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.