In Rails 5 Active Record provide two finder methods to specify JOIN on associated tables,

Suppose in our application we have Article and Comment. Here comments belong to an article, while article have many comments.
Now if we want to show list of all articles along with number of comments, we need join to Article and Comment by left_outer_join.

In rails 4.x, Active Record does not have support for outer joins. So we need to add SQL for left outer join manually.

articles = Article.join('LEFT OUTER JOIN "comments" ON "comments"."article_id" = "articles"."id"')
            .select("articles.*, COUNT(comments.*) as comment_count")

But Rails 5 has added left_outer_joins method, and we can use it as:

articles = Article.left_outer_joins(:comments)
                .select("articles.*, COUNT(comments.*) as comment_count")

We can use left_outer_joins to perform left outer join on multiple tables at same time as well.

Article.left_outer_joins(:comments, :viewers)

Rails 5 also have alias method for left_outer_joins as left_joins


Thank You!