Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple nested includes in Rails

Let's say I have four models, Groups, Users, Posts and Comments in my Rails 3 app. The relation is:

Groups has_many Users
Users has_many Posts
Posts has_many Comments

(and all with belongs_to in the other direction)

How do I get all comments that belongs to a group.id in one query? I can not stop thinking of using multiple includes() (but without success so far) like

comments = Comment.includes(:Post).includes(:User).includes(:Group).where("groups.id IS ?", group.id)
like image 738
kernification Avatar asked Apr 29 '14 11:04

kernification


1 Answers

You can use eager_load method:

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

You can find more info about this type of queries in this blog post.

like image 124
Marek Lipka Avatar answered Oct 13 '22 05:10

Marek Lipka