回形针 - 动态使用:路径

时间:2014-12-27 16:57:12

标签: ruby-on-rails ruby paperclip

我正在使用paperclip来附加文件。

在我的情况下,我想为每个文档保存附件。

所以,我的回形针模型类看起来像

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的值) 我该怎么办?

1 个答案:

答案 0 :(得分: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