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

       `joins`
       `left_outer_joins`

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"')
            .distinct
            .select("articles.*, COUNT(comments.*) as comment_count")
            .group("articles.id")

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

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

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

Article.left_joins(:comments)

Thank You!

Your comment

*

*