渴望加载多态关联的关联

时间:2014-04-16 11:02:23

标签: ruby-on-rails activerecord ruby-on-rails-4 polymorphism eager-loading

class Flat < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

class Agency < ActiveRecord::Base
  has_many :flats, as: :owner
end

class User < ActiveRecord::Base
  has_many :flats, as: :owner
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

Flat.includes(:owner)工作正常,但Flat.includes(owner: :profile)代理商会失败。如何仅在flats.owner_type == "User"时包含个人资料才能阻止N + 1个查询?

1 个答案:

答案 0 :(得分:0)

使用squeel,您可以轻松完成此操作:

Flat.joins{owner(User).profile}.includes(owner: :profile).first.owner.profile
Flat.joins{owner(Agency)}.includes(owner).first.owner

此查询将用户1 + n查询。