ker*_*ion 12 activerecord ruby-on-rails
假设我的Rails 3应用程序中有四个模型,组,用户,帖子和评论.关系是:
Groups has_many Users
Users has_many Posts
Posts has_many Comments
Run Code Online (Sandbox Code Playgroud)
(以及所有与另一方向的belongs_to)
如何在一个查询中获取属于group.id的所有注释?我不能不再考虑使用多个includes()(但到目前为止没有成功)
comments = Comment.includes(:Post).includes(:User).includes(:Group).where("groups.id IS ?", group.id)
Run Code Online (Sandbox Code Playgroud)
您仍然可以使用包含
comments = Comment.includes(post: {user: :group}).where('groups.id = ?', group.id)
Run Code Online (Sandbox Code Playgroud)
看到这个题目在Rails 4.1指南
你可以使用eager_load方法:
comments = Comment.eager_load(post: {user: :group}).where('groups.id = ?', group.id)
Run Code Online (Sandbox Code Playgroud)
您可以在此博客文章中找到有关此类查询的更多信息.