ruby-on-rails – Ruby on Rails – 如何委托多态关联?

是否可以在多态模型中使用has_many或has_one关联的委托?这是如何运作的?

class Generic < ActiveRecord::Base
    ...

  belongs_to :generable, polymorphic: true

  delegate :file_url, to: :image, allow_nil: true
  delegate :type_cat, to: :cat, allow_nil: true
end

class Image < ActiveRecord::Base
   ...
  has_one :generic, as: generable, dependent: :destroy
end


class Cat < ActiveRecord::Base
   ...
  has_one :generic, as: generable, dependent: :destroy
end
最佳答案
不确定这是否与你想要做的完全匹配,因为从你的例子中很难说但是……

class Generic < ActiveRecord::Base
  ...
  belongs_to :generable, polymorphic: true
  ...
  delegate :common_method, to: :generable, prefix: true
end

class Cat
  def common_method
    ...
  end
end

class Image
  def common_method
    ...
  end
end

允许您说出以下内容:

generic.generable_common_method

转载注明原文:ruby-on-rails – Ruby on Rails – 如何委托多态关联? - 代码日志