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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With