High
Rails
Avoid N+1 queries
Official
Rule Description
Use eager loading to prevent N+1 queries:
- `includes`: For associations you'll access
- `preload`: Force separate queries (useful for complex conditions)
- `eager_load`: Force LEFT OUTER JOIN
Use the Bullet gem in development to detect N+1 queries automatically.
```ruby
# Bad: N+1 queries
@posts = Post.all
@posts.each { |p| p.author.name } # Queries author for each post
# Good: Eager loading
@posts = Post.includes(:author)
@posts.each { |p| p.author.name } # Single query for authors
```
Add This Rule
Sign in to add this rule to your workspace
Sign in with GitHubDetails
- Severity
- High
- Category
- Rails
- Used in
- 2 rulesets