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
  • .count inside a loop (where counter_cache or 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 preloaded scope that bundles the standard eager-loads for that model — call it everywhere the view is rendered (Gierd convention from rails-models)
  • For counts, use counter_cache or LEFT JOIN ... GROUP BY aggregation rather than .count in a loop
  • Verify with Bullet in dev or assert_queries(N) in tests
Installs
2
First Seen
May 8, 2026
rails-antipattern-n-plus-one-in-views — gierd-inc/dev-skills