简体   繁体   English

使用Paperclip gem动态生成Amazon S3资产的文件路径

[英]Dynamically generating file path for Amazon S3 assets with Paperclip gem

I'm successfully using the Paperclip gem to upload files to Amazon S3. 我已成功使用Paperclip gem将文件上传到Amazon S3。 My question is, how can I configure my model to change the file path based on object attributes? 我的问题是,如何配置模型以基于对象属性更改文件路径?

For example, I want an image of a 2015 RAM 1500 to be uploaded to "cars/2015/RAM/1500/:id." 例如,我希望将2015 RAM 1500的图像上载到“ cars / 2015 / RAM / 1500 /:id”。

Here's what I tried. 这是我尝试过的。 The ":id/:style_:extension" gets replaced with the correct information, but the other attributes do not - even though each car has a year, manufacturer, and model. “:id /:style_:extension”将替换为正确的信息,但其他属性则不会被替换-即使每辆汽车都有年份,制造商和型号。

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

Ok, it's in the docs (oops): Paperclip Interpolations 好的,它在文档(哎呀)中: 回形针插值

I added this block for each attribute I needed to interpolate to my car model: 我为需要插值到汽车模型中的每个属性添加了此块:

Paperclip.interpolates :year do |attachment, style|
  attachment.instance.year
end

Here's another way you could do it, which is pretty clean and reusable. 这是您可以做的另一种方法,它很干净而且可重用。 While Concerns are sometimes frowned upon, this is one of the cases when they are very useful! 尽管有时会感到担忧,但这是非常有用的情况之一!

# 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

And then, in any of your models: 然后,在您的任何模型中:

# models/car.rb
class Car < ApplicationRecord
  include Interpolates

  interpolates :manufacturer

  # ...
end

And then, you can use that in any model you want, with very little code! 然后,您只需很少的代码就可以在所需的任何模型中使用它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM