2012-03-21 40 views
1

我使用附件模型作爲多態關聯。如何根據關聯更改路徑和網址參數。回形針自定義路徑和多態關聯網址

附件模型

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/ 

回答

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 
+0

感謝@artimuz工作正常 – Prasanna 2012-03-21 09:02:36

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