Rails多态关联覆盖了吸气器的加载

时间:2014-04-29 13:22:06

标签: ruby-on-rails ruby ruby-on-rails-3 polymorphic-associations

我的设计很可怕。它与重写的getter具有多种多态关系,例如

class Whtvr
  belongs_to :assoc, polymorphic: true

  def assoc
    if assoc_type == 'a_type'
      AType.find(assoc_id)
    else
      BaseType.find(assoc_id)
    end
  end
end

我怎样才能使这个可以加载?

Whtvr.includes(:assoc).find(1, 2, 3)

1 个答案:

答案 0 :(得分:1)

即使吸气剂没有被覆盖,你也不会急于加载多态关联。

您需要为每种类型的关联定义belongs_to

belongs_to :a_type, class_name: "AType", foreign_key: "assoc_id"

belongs_to :base_type, class_name: "BaseType", foreign_key: "assoc_id"

然后,根据你想做的事情,使用另一个。

Whtvr.includes(:a_type).find(1)
相关问题