Ruby on rails 使用曲别针动态生成Amazon S3资产的文件路径
我成功地使用回形针gem将文件上传到AmazonS3。我的问题是,如何配置模型以基于对象属性更改文件路径 例如,我希望将2015 RAM 1500的图像上载到“cars/2015/RAM/1500/:id” 这是我试过的。“:id/:style_:extension”将被正确的信息替换,但其他属性不会被替换,即使每辆车都有年份、制造商和型号Ruby on rails 使用曲别针动态生成Amazon S3资产的文件路径,ruby-on-rails,amazon-s3,paperclip,Ruby On Rails,Amazon S3,Paperclip,我成功地使用回形针gem将文件上传到AmazonS3。我的问题是,如何配置模型以基于对象属性更改文件路径 例如,我希望将2015 RAM 1500的图像上载到“cars/2015/RAM/1500/:id” 这是我试过的。“:id/:style_:extension”将被正确的信息替换,但其他属性不会被替换,即使每辆车都有年份、制造商和型号 class Car < ActiveRecord::Base has_attached_file :file, default_url: "/im
class Car < ActiveRecord::Base
has_attached_file :file, default_url: "/images/:style/missing.png"
validates_attachment_content_type :file, content_type: /\Aimage\/.*\Z/
has_attached_file :file,
:storage => :s3,
:path => "cars/:year/:manufacturer/:model/:id/:style_:extension",
:s3_credentials => Proc.new{|a| a.instance.s3_credentials }
belongs_to :manufacturer
def s3_credentials
{:bucket => ENV['bucket'], :access_key_id => ENV['access_key_id'], :secret_access_key => ENV['secret_access_key']}
end
end
class-Car:s3,
:path=>cars/:year/:manufacturer/:model/:id/:style\uu:extension“,
:s3_credentials=>Proc.new{| a | a.instance.s3_credentials}
属于:制造商
def s3_凭证
{:bucket=>ENV['bucket'],:access_key_id=>ENV['access_key_id'],:secret_access_key=>ENV['secret_access_key']
结束
结束
好的,它在文档中(oops):
我为每个需要插值到汽车模型的属性添加了此块:
Paperclip.interpolates :year do |attachment, style|
attachment.instance.year
end
这里有另一种方法,非常干净,可以重复使用。虽然担忧有时是不受欢迎的,但这是它们非常有用的情况之一
# lib/interpolates.rb
module Interpolates
extend ActiveSupport::Concern
included do
def self.interpolates(attr)
Paperclip.interpolates(attr) do |attachment, style|
attachment.instance.send(attr)
end
end
end
end
然后,在您的任何型号中:
# models/car.rb
class Car < ApplicationRecord
include Interpolates
interpolates :manufacturer
# ...
end
#models/car.rb
类车<应用记录
包含插值
插入:制造商
# ...
结束
然后,您可以在任何您想要的模型中使用它,只需很少的代码