Rails N+1 Query Problem and its Solution

Rails N+1 Query Problem and its Solution

29 October 2021

Introduction to Problem

To understand the problem let’s create one project having Author and Book as models.

Example:

  1. rails g model Book name:string details:text
  2. rails g model Author name:text

Models

Rails N+1 Query Problem and its Solution

Rails N+1 Query Problem and its Solution

Migrations

Rails N+1 Query Problem and its Solution

Rails N+1 Query Problem and its Solution

Now let’s add the number of authors inside the authors table and create multiple books for each author. After that, open the rails console and try to find all books associated with each author.

Rails Console

Rails N+1 Query Problem and its Solution

As we can see when we try to fetch books having authors, the authors table query is executed multiple times that directly affects the application performance.  In simple words, we have tried to fetch N books using 1 query (Book.all) but when we tried to fetch associated records subsequently N extra queries were executed so total N+1 queries were used to find the records.

How to Solve this?

The common solution that is used to solve this problem is eager loading with methods like preload, includes, eager_load.

Preload:

Rails N+1 Query Problem and its Solution

Preload method executes only two methods, in this case, one for books and another for authors, but we can not add a where clause with the preload method.

Includes:

Rails N+1 Query Problem and its Solution

On the other hand, the includes method also executes two queries in this case but we can add where clause method to execute with conditions.

Eager Load:

Rails N+1 Query Problem and its Solution

The eager load method uses only one query with LEFT OUTER JOIN to find the records.

search

Blog Categories

Request a quote