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
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.
Rails 5 also have alias method for
Subscribe to Engineering At Kiprosh
Get the latest posts delivered right to your inbox