ruby-on-rails - 回形针 - 动态使用 :path

标签 ruby-on-rails ruby 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 的值) 我该怎么做?

最佳答案

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

关于ruby-on-rails - 回形针 - 动态使用 :path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27669413/

相关文章:

ruby-on-rails - 在Ruby/Rails中,如何解密由PKCS7加密和签名的字符串

ruby - 条件语句出现在表达式之前还是之后有关系吗?

javascript - 通过 AWS Ruby SDK 将 Base64 图像数据上传到 S3

ruby-on-rails - ActiveRecord 类方法返回 `self` 丢失间接引用

ruby-on-rails - 使用 ruby​​ 创建常用单词或短语列表

ruby-on-rails - 获取回形针附件的绝对 URL

ruby-on-rails - Ruby on Rails PaperClip Gem 验证附件错误

ruby-on-rails - Paperclip::AdapterRegistry::NoHandlerError(未找到 ""的处理程序)

ruby-on-rails - 符合 I18n 标准的中文语言环境

ruby-on-rails - 将临时变量传递给模型进行处理