Benito Serna Tips and tools for Ruby on Rails developers

What is an n+1 queries problem?

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

class Comment < ActiveRecord::Base
  belongs_to :post

If you execute the next code…

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

You will execute…

If there are…

Related articles

Do you want to solve n+1 queries with confidence?

Sign up to download free ebook, where I will show the basics on how to deal with n+1 problems.

  • Understand the methods (joins, includes, etc...) to work with associations.
  • Identify when active record will execute a query.
  • And the tools that can help you detect n+1 queries (like the bullet gem).