Today I Learned

A Hashrocket project

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

Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket and we'd love to take a look at your project. Contact us and find out how we can help you.