How to Use Joins in Ruby on Rails

09/19/2021

Contents

In this article, you will learn how to use joins in Ruby on Rails.

How to use joins

Joins in Ruby on Rails allow you to query data from multiple database tables by combining the data into a single result set. This is useful when you need to access data from related tables in your Rails application. There are several ways to use joins in Ruby on Rails, depending on the type of join you want to perform and the complexity of your query.

Here are some examples:

Inner Join

An inner join returns only the records that have matching values in both tables. Here’s an example of how to use an inner join in Rails:

User.joins(:orders).where("orders.created_at >= ?", Time.now - 1.week)

This query will join the “users” and “orders” tables and return only the users who have placed an order in the last week.

Left Outer Join

A left outer join returns all the records from the first (left) table and the matching records from the second (right) table. If there is no match in the second table, NULL values will be returned. Here’s an example of how to use a left outer join in Rails:

User.left_outer_joins(:orders).where("orders.created_at IS NULL")

This query will join the “users” and “orders” tables and return only the users who have not placed any orders.

Right Outer Join

A right outer join returns all the records from the second (right) table and the matching records from the first (left) table. If there is no match in the first table, NULL values will be returned. Here’s an example of how to use a right outer join in Rails:

Order.right_outer_joins(:user).where("users.name LIKE ?", "%john%")

This query will join the “orders” and “users” tables and return only the orders placed by users whose name contains the word “john”.

Full Outer Join

A full outer join returns all the records from both tables, with NULL values for non-matching records. Here’s an example of how to use a full outer join in Rails:

User.joins("FULL OUTER JOIN orders ON users.id = orders.user_id")

This query will perform a full outer join between the “users” and “orders” tables, returning all the users and orders, with NULL values for non-matching records.