Rails N+1 Query Fix: includes and strict_loading
An N+1 runs one query for the list and one more per row. We measured 3 users with 3 posts each: looping posts and calling post.user.name ran 10 queries. Adding includes cut it to 2.
Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.
The conversion
SQL
SELECT * FROM posts;
SELECT * FROM users WHERE id = 1;
SELECT * FROM users WHERE id = 2;
SELECT * FROM users WHERE id = 3;
-- one query per post
ActiveRecord
Post.includes(:user).each { |post| post.user.name }
SQL that Rails 8.1.1 generates
SELECT X "users".* FROM "users" WHERE "users"."id" IN ($1, $2, $3)
A cleaner alternative
Post.strict_loading.first.user
strict_loading raises ActiveRecord::StrictLoadingViolationError the moment an association loads lazily. Use it in tests and development to catch N+1 before production.
Related form
SELECT * FROM users;
SELECT * FROM posts WHERE user_id IN (1, 2, 3);
SELECT * FROM comments WHERE post_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9);
User.includes(posts: :comments).each { |u| u.posts.each { |p| p.comments.size } }
What goes wrong
Count the queries, do not guess
Looping Post.all and reading post.user ran 10 queries for 9 posts. Post.includes(:user) ran 2. The nested includes example ran 3 queries for 3 levels.
count still queries after includes
With User.includes(:posts), calling u.posts.size ran 2 queries in total. Calling u.posts.count ran 5. count always sends SQL. Use size or length on a loaded association.
joins does not fix N+1
Post.joins(:user).each { |p| p.user.name } still ran 10 queries. joins builds a JOIN but does not load the association. See the joins vs includes page.
Do not include what you do not read
includes loads every user row it finds. If the view only needs the name, use joins with select or pluck to avoid building objects.
Convert your own N+1 query query
Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.
Questions
How do I fix an N+1 query in Rails?
Load the association up front with includes, preload or eager_load. Then confirm the query count dropped, for example from 10 to 2.
How do I detect N+1 queries in Rails?
Use strict_loading in development and tests. It raises on lazy loading. The Bullet gem also reports N+1s from a running app.
Does includes always fix N+1?
Only for associations you read. It also does nothing if you call count on the association, because count always runs SQL.
Related conversions
Rails includes vs preload vs eager_load
includes, preload and eager_load compared with the real SQL from Rails 8.1 and PostgreSQL 16. See which runs 2 queries, which runs a JOIN, and which fails.
Rails joins vs includes
Rails joins vs includes with measured query counts and real SQL from Rails 8.1 and PostgreSQL 16. joins filters, includes loads, and joins does not fix N+1.
ActiveRecord explain: Read the Query Plan
Run EXPLAIN and EXPLAIN ANALYZE from ActiveRecord with relation.explain. Real PostgreSQL 16 plan output, options like :buffers, and how to read Seq Scan.
All SQL converters
Every tested SQL to ActiveRecord conversion on this site.
Safe conversion guide
How to check that a converted query returns the same rows.