Outer join with ActiveRecord `references` method
I want to join posts
to comments
regardless if comments exist or not.
You can use includes
for that:
Post.includes(:comments).all
But that results in 2 queries, one to get all the posts, and one to get all comments that have the relevant post_id.
With references
you can turn this into an outer join:
Post.includes(:comments).references(:comments).all
Now we're getting all the information we need with just 1 query.
Check out the Active Record guides here
Tweet