X

Difference Between includes and joins in Ruby on Rails

When working with databases in Ruby on Rails, you'll often need to retrieve data from multiple tables. Two common methods for doing this are includes and joins.

When working with databases in Ruby on Rails, you'll often need to retrieve data from multiple tables. Two common methods for doing this are includes and joins. While both can be used to fetch associated data, they work differently under the hood. In this blog, we'll dive into the differences between includes and joins.

joins: The SQL Join
joins is a method in Rails that corresponds to an SQL JOIN operation. It's used to fetch data by creating a SQL query that combines records from two or more database tables. This is particularly useful when you need to filter records based on conditions in associated tables.
It uses lazy loading, which means that associated data is retrieved when needed. If you have a collection of records, using joins will not load associated records immediately but only when you try to access them.
It's useful when you need to retrieve data from multiple tables, often to filter or sort records based on columns from associated tables.
Example:
Suppose we have two models, Author and Book, and we want to retrieve all books by a specific author.

Author.joins(:books).where(name: 'John Doe').select('books.title')

This generates a SQL query with an inner join between the authors and books tables.

includes: Eager Loading
includes, on the other hand, is used for eager loading of associations. It helps you optimize data retrieval and avoids the N+1 query problem. When you use includes, Rails loads the associated data upfront in a separate query, reducing the number of database queries.
Example:
Let's say we want to list authors and their books. Using includes, we can load both author and book data efficiently.

authors = Author.includes(:books)
authors.each do |author|
  puts author.name
  author.books.each do |book|
    puts book.title
  end
end

Here, Rails generates two SQL queries - one for authors and another for books - instead of loading books for each author individually.

Summary
Use joins when you need to perform SQL joins and filter records based on conditions in associated tables.
Use includes for eager loading to optimize data retrieval and avoid the N+1 query problem.
Understanding the differences between includes and joins is essential for efficient database operations in Ruby on Rails. Choose the method that best fits your use case to build performant and scalable applications.