问题 Rails中有多个嵌套包含


假设我的Rails 3应用程序中有四个模型,组,用户,帖子和评论。关系是:

Groups has_many Users
Users has_many Posts
Posts has_many Comments

(以及所有与另一方向的belongs_to)

如何在一个查询中获取属于group.id的所有注释? 我不能不再考虑使用多个includes()(但到目前为止没有成功)

comments = Comment.includes(:Post).includes(:User).includes(:Group).where("groups.id IS ?", group.id)

10009
2018-04-29 11:57


起源



答案:


您可以使用 eager_load 方法:

comments = Comment.eager_load(post: {user: :group}).where('groups.id = ?', group.id)

您可以在此找到有关此类查询的更多信息 博客文章


6
2018-04-29 12:00



不能用它 includes? - Pavan
@Pavan它可以工作,但它在Rails 4中已被弃用。 - Marek Lipka
没有任何理由可以使用 eager_load 过度 includes 在这里,它可能会根据条件改变结果。 - Andrew Marshall
@AndrewMarshall如何根据条件改变结果? - Marek Lipka
哎呀,我想我在考虑 preload。也 includes 本身并没有被弃用的AFAIK,只是它的某些用途。 - Andrew Marshall


答案:


您可以使用 eager_load 方法:

comments = Comment.eager_load(post: {user: :group}).where('groups.id = ?', group.id)

您可以在此找到有关此类查询的更多信息 博客文章


6
2018-04-29 12:00



不能用它 includes? - Pavan
@Pavan它可以工作,但它在Rails 4中已被弃用。 - Marek Lipka
没有任何理由可以使用 eager_load 过度 includes 在这里,它可能会根据条件改变结果。 - Andrew Marshall
@AndrewMarshall如何根据条件改变结果? - Marek Lipka
哎呀,我想我在考虑 preload。也 includes 本身并没有被弃用的AFAIK,只是它的某些用途。 - Andrew Marshall


您仍然可以使用包含

comments = Comment.includes(post: {user: :group}).where('groups.id = ?', group.id)

看到这个 话题 在 Rails 4.1 指南


8
2018-04-29 12:22