Benito Serna Tips and tools for Ruby on Rails developers

What is an n+1 queries problem?

July 27, 2021

An n+1 queries problem means that a query is executed for every result of a previous query.

For example, with this records…

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

If you execute the next code…

Post.all.each do |post|
  post.comments.each do |comment|
    puts comment.body
  end
end

You will execute…

If there are…

Related articles

Download a free ebook to learn the basics of n+1 queries on Rails basics

Learn just enough fundamentals to be fluent preloading associations with ActiveRecord, and start helping your team to avoid n+1 queries on production.