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
endFlat.includes(:owner)工作得很好,但对于代理来说,Flat.includes(owner: :profile)将失败。如何在flats.owner_type == "User"时包含仅配置文件,以防止N+1查询?
发布于 2014-04-17 19:16:03
使用squeel,您可以轻松地做到这一点:
Flat.joins{owner(User).profile}.includes(owner: :profile).first.owner.profile
Flat.joins{owner(Agency)}.includes(owner).first.owner此查询将使用1+n查询。
https://stackoverflow.com/questions/23107556
复制相似问题