rails-antipattern-n-plus-one-in-views
Installation
SKILL.md
Antipattern: N+1 Queries (especially in views)
The smell
- Iterating a collection that calls
.author,.comments.count, or other associations per row - 50+ "SELECT ... WHERE id = ?" queries in dev log for one page render
- Bullet gem warnings
.countinside a loop (wherecounter_cacheor aggregation would do)
Why it hurts
- Latency scales linearly with rows
- DB connection pressure
- Slow in dev, catastrophic in prod
- Often invisible until production data shape changes
The fix
- Eager-load in the controller or scope:
Post.includes(:author).recent - Define a
preloadedscope that bundles the standard eager-loads for that model — call it everywhere the view is rendered (Gierd convention fromrails-models) - For counts, use
counter_cacheorLEFT JOIN ... GROUP BYaggregation rather than.countin a loop - Verify with Bullet in dev or
assert_queries(N)in tests