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:
- rails g model Book name:string details:text
- rails g model Author name:text
Models
Migrations
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
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:
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:
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:
The eager load method uses only one query with LEFT OUTER JOIN to find the records.