【问题标题】:Dynamically generating file path for Amazon S3 assets with Paperclip gem使用 Paperclip gem 为 Amazon S3 资产动态生成文件路径
【发布时间】:2016-03-18 18:04:06
【问题描述】:

我已成功使用 Paperclip gem 将文件上传到 Amazon S3。我的问题是,如何配置我的模型以根据对象属性更改文件路径?

例如,我希望将 2015 RAM 1500 的图像上传到“cars/2015/RAM/1500/:id”。

这是我尝试过的。 ":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

【问题讨论】:

    标签: ruby-on-rails amazon-s3 paperclip


    【解决方案1】:

    好的,它在文档中(哎呀):Paperclip Interpolations

    我为需要插入汽车模型的每个属性添加了这个块:

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

    【讨论】:

      【解决方案2】:

      这是另一种方法,它非常干净且可重复使用。尽管有时不赞成关注,但这是它们非常有用的情况之一!

      # 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
      

      然后,您可以在任何您想要的模型中使用它,只需很少的代码!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多