回形针自定义路径和用于多态关联的URL

时间:2012-03-21 07:21:36

标签: ruby-on-rails-3 paperclip

我使用附件模型作为多态关联。如何根据关联更改路径和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",

但我需要保存基于关联的文件,为此如何将参数传递给'path'。 'attachable_type'定义了哪个关联上传文件属于

/attachments/project/
/attachments/client/

2 个答案:

答案 0 :(得分:6)

您可以使用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

答案 1 :(得分:0)

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