Avoid N+1 Queries

Prevent the N+1 query problem that causes excessive database queries.

Understanding N+1

The N+1 problem occurs when fetching a collection (1 query) and then accessing a relationship for each item (N queries).

The Problem

# 1 query to fetch posts
posts = Post.all

# N queries - one for each post's author!
posts.each do |post|
  puts post.user.name  # Triggers a query each time
end

With 100 posts, this runs 101 queries.

Use Eager Loading

Load relationships upfront with batch queries using preload.

Basic Preload

Multiple Relationships

Use Joins for Filtering

When filtering by associated records:

Select Only Needed Columns

Reduce memory by selecting specific columns:

Batch Loading

For custom relationships or complex scenarios:

Detecting N+1 Queries

Enable query logging during development:

Look for repeated similar queries:

Common N+1 Scenarios

In Views/Templates

Manual Counter Columns

For frequently accessed counts, add a counter column and maintain it manually:

Aggregations

Verify Fix

Before:

After:

See Also

Last updated

Was this helpful?