How To Avoid N + 1 problem in Rails

How To Avoid N + 1 problem in Rails hackernoon.com2 years ago in #Dev Love55

@kalavhanJosué Full stack web developer Ruby | JavaScript | PHP | CSS | RoR Almost any app that we build has a lot of interactive options with a lot of data, to this we can also have conditions to which data should we show to what type of user, making us request data from different tables based on a unique identifier, if the queries are not handled in a proper manner this can slow down the loading, and that is because of the “N 1” problem. What is the “N 1” problem? The problem occurs when we have to make a query to get each of the associations, “1” being the first query to get the parent and “N” the number of queries required to get all the associations, let’s take a look into an example. author.rb class Author < ApplicationRecord has_many :articles end article.rb class Article < ApplicationRecord belongs_to :author end articles_controller.rb class SalesController < ApplicationController def index @articles_list = Article.where("created_at >= ? AND created_at = ? AND published_at = ? AND published_at = ? AND published_at  » Read More

Like to keep reading?

This article first appeared on If you'd like to keep reading, follow the white rabbit.

View Full Article

Leave a Reply