【问题标题】:paperclip custom path and url for polymorphic associations用于多态关联的回形针自定义路径和 url
【发布时间】:2012-03-21 07:21:35
【问题描述】:

我使用附件模型作为多态关联。如何根据关联更改路径和 url 参数。

附件模型

class Attachment < ActiveRecord::Base
  belongs_to :user
  belongs_to :attachable, :polymorphic => true

  has_attached_file :attachment,
                    :url  => "/attachments/:id/:basename.:extension",
                    :path => ":rails_root/public/attachments/:id/:basename.:extension",
                    :default_url => "/attachments/original/no-file.txt"
end

项目模型

class Project < ActiveRecord::Base
 ...
 has_many :attachments, :as => :attachable, :dependent => :destroy
end

客户

class Client < ActiveRecord::Base
 ...
 has_many :attachments, :as => :attachable, :dependent => :destroy
end

以下路径文件保存正常。

:path => ":rails_root/public/attachments/:id/:basename.:extension",

但我需要根据关联保存文件,为此如何将参数传递给“路径”。 'attachable_type' 定义了上传文件属于哪个关联

/attachments/project/
/attachments/client/

【问题讨论】:

    标签: ruby-on-rails-3 paperclip


    【解决方案1】:

    您可以使用Paperclip Interpolations。插值允许您调用一个方法来确定路径的一部分的值。

    class Attachment < ActiveRecord::Base
      belongs_to :user
      belongs_to :attachable, :polymorphic => true
    
      Paperclip.interpolates :attached_to do |attachment, style|
        attachment.instance.attachable.class.to_s.downcase
      end
    
      has_attached_file :attachment,
                        :url  => "/attachments/:id/:basename.:extension",
                        :path => ":rails_root/public/attachments/:attached_to/:id/:basename.:extension",
                        :default_url => "/attachments/original/no-file.txt"
    end
    

    【讨论】:

      【解决方案2】:
      has_attached_file :attachment, :path => ":rails_root/public/attachments/#{lambda { |a| a.instance.images_path? ? 'project' : 'client' }}/:id/:basename.:extension"
      
      
      
      def images_path?
          if your pretty condition  
            #return true
          else
            #return false 
          end
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多