Asia

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.

Tudip Technologies

Tudip Technologies is a value-driven Software Services company. We deliver excellence in dedicated and business-centric web solutions incorporated with innovation and expertise as the tools to achieve business goals. Our high-quality, cost-effective, reliable, and scalable services have helped us build an enduring relationship with our clients and customers.

Latest Posts

  • All Posts
  • Casestudy
  • Cloud
  • Healthcare
  • Ios
  • IOT
  • Java
  • Manufacturing
  • News
  • OTT
  • Supply Chain
  • Support and Maintainance
    •   Back
    • Banking
Cloud-Powered Agility

December 27, 2024

27 December 2024 Introduction: Transforming Chaos into Opportunity Imagine a supply chain where disruptions are predicted before they occur, inventory…

Cloud-Powered Agility

December 24, 2024

Imagine a supply chain where disruptions are predicted before they occur, inventory is optimized in real-time, and every stakeholder works…

Related Posts

  • All Posts
  • Healthcare