如何在保存多态对象的父级之前获取它?

Ric*_*urt 4 polymorphism ruby-on-rails paperclip

我有一个标准的多态关系,我需要在保存它之前知道它的父亲是谁.

Class Picture < AR::Base
  belongs_to :attachable, :polymorphic => true
end

Class Person < AR::Base
  has_many :pictures, :as => :attachable
end

Class Vehicle < AR::Base
  has_many :pictures, :as => :attachable
end
Run Code Online (Sandbox Code Playgroud)

我正在通过Paperclip上传图片,我构建了一个处理器,需要对不同的图片做不同的事情(即人物图片应该有宝丽来的外观,车辆图片应该有叠加).我的问题是在保存图片之前我不知道它是否与人或车辆相关联.

我尝试在Person&Vehicle中放置一个"标记",以便我可以告诉他们appart,但是当我在Paperclip处理器中时,我唯一看到的是Picture类.:(我的下一个想法是爬上堆栈试图让父母打电话,但这对我来说似乎很臭.你会怎么做?

Ben*_*Ben 5

您应该能够从多态关联中获取它.

Class Picture < AR::Base
  belongs_to :attachable, :polymorphic => true

  before_create :apply_filter

  private

  def apply_filter
    case attachable
    when Person
      #apply Person filter
    when Vehicle
      #apply Vehicle filter
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

或者,您可以问它关联类型,因此它不必构建和比较对象,而只是进行字符串比较.

Class Picture < AR::Base
  belongs_to :attachable, :polymorphic => true

  before_create :apply_filter

  private

  def apply_filter
    case attachable_type
    when "Person"
      #apply Person filter
    when "Vehicle"
      #apply Vehicle filter
    end
  end
end
Run Code Online (Sandbox Code Playgroud)