Rails 5 - 使用回形针的动态样式的多态附件

时间:2016-07-13 17:06:00

标签: ruby-on-rails ruby polymorphism paperclip ruby-on-rails-5

我正在尝试使用paperclip创建具有动态样式的多态附件类,并将其用于另一个类(Foo)。

我有附件类:

class Attachment < ApplicationRecord

  belongs_to :attachable, polymorphic: true, optional: true

  has_attached_file :attachment,
    styles: ->(a) {a.instance.attachable.attachment_styles}

  validates_attachment_content_type :attachment, content_type: /\Aimage\/.*\Z/
end

和Foo类:

class Foo < ApplicationRecord
  has_many :attachments, class_name: "Attachment", as: :attachable, dependent: :destroy
  accepts_nested_attributes_for :attachments

  def attachment_styles
    {
     :thumb => "30x30>",
     :medium => "100x100>"
    }
  end
end

这里的问题是我在lambda函数里面还没有foo对象。 a.instance.attachable返回nil。

我得到的错误是:

NoMethodError: undefined method `attachment_styles' for nil:NilClass

我正在使用Rails 5和paperclip 5.0.0。 我认为这适用于Rails 4。

PS:我需要风格是动态的,因为我将使用来自多个模型的附件,而不仅仅是来自Foo。

0 个答案:

没有答案
相关问题