Avoid N+1 Queries
Understanding N+1
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
endUse Eager Loading
Basic Preload
Multiple Relationships
Use Joins for Filtering
Select Only Needed Columns
Batch Loading
Detecting N+1 Queries
Common N+1 Scenarios
In Views/Templates
Manual Counter Columns
Aggregations
Verify Fix
See Also
Last updated
Was this helpful?