2014-12-27 80 views
1

我使用回形針來附加文件。回形針 - 動態使用:路徑

在我的情況下,我想保存每個文檔的附件。

所以,我的回形針模型類看起來像

class Attachment < ActiveRecord::Base 
    self.table_name = 'attachments' 
    self.primary_key = 'srl' 

    @@document_srl 

    validates :document_srl, 
      :presence => true, 
      :numericality => { only_integer: true }, 
      allow_nil: false 

    has_attached_file :attached, 
        :path => :save_path 
    validates_attachment_content_type :attached, :content_type => /\Aimage\/.*\Z/ 

    def save_path 
    ":attachment/#{@@document_srl}/:id/:style/:filename" 
    end 
end 

has_attached_file,我要生成路徑動態爲document_srl有關。 (我將在創建此模型的實例時設置document_srl的值) 我該怎麼做?

回答

3

我們可以使用Paperclip.interpolates進行這項工作。

class Attachment < ActiveRecord::Base 
    self.table_name = 'attachments' 
    self.primary_key = 'srl' 

    validates :document_srl, 
      :presence => true, 
      :numericality => { only_integer: true }, 
      allow_nil: false 

    has_attached_file :attached, 
        :path => ":attachment/:document_srl/:id/:style/:filename" 
    validates_attachment_content_type :attached, :content_type => /\Aimage\/.*\Z/ 

    Paperclip.interpolates :document_srl do |attachment, style| 
    attachment.instance.document_srl 
    end 
end 
+0

我試圖使用它,但沒有完成它,我有一個控制器和一個模型。你能解釋我怎樣才能使路徑動態?我試圖從控制器傳遞文件夾路徑作爲參數。 – 2015-09-05 02:10:37

+0

有關此鏈接的更多信息https://github.com/thoughtbot/paperclip/wiki/Interpolations – 2017-04-20 06:22:13