回形针 - 动态使用:路径
问题描述:
我使用回形针来附加文件。回形针 - 动态使用:路径
在我的情况下,我想保存每个文档的附件。
所以,我的回形针模型类看起来像
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的值) 我该怎么做?
答
我们可以使用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
我试图使用它,但没有完成它,我有一个控制器和一个模型。你能解释我怎样才能使路径动态?我试图从控制器传递文件夹路径作为参数。 – 2015-09-05 02:10:37
有关此链接的更多信息https://github.com/thoughtbot/paperclip/wiki/Interpolations – 2017-04-20 06:22:13