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_Query_Problem_and_its_Solution_01

Rails_Query_Problem_and_its_Solution_02

Migrations

Rails_Query_Problem_and_its_Solution_03

Rails_Query_Problem_and_its_Solution_04

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_Query_Problem_and_its_Solution_05

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_Query_Problem_and_its_Solution_06

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_Query_Problem_and_its_Solution_07

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_Query_Problem_and_its_Solution_08

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

search
Blog Categories
Request a quote