首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >立即加载多态关联的关联

立即加载多态关联的关联
EN

Stack Overflow用户
提问于 2014-04-16 19:02:23
回答 1查看 89关注 0票数 2
代码语言:javascript
复制
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查询?

EN

回答 1

Stack Overflow用户

发布于 2014-04-17 19:16:03

使用squeel,您可以轻松地做到这一点:

代码语言:javascript
复制
Flat.joins{owner(User).profile}.includes(owner: :profile).first.owner.profile
Flat.joins{owner(Agency)}.includes(owner).first.owner

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23107556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档