rails-query-optimization

Optimize ActiveRecord queries to prevent N+1 problems in Rails APIs.

4|Updated Feb 16, 2017
One-click install
npx skills add https://github.com/nekorush14/dotfiles --skill rails-query-optimization
Or copy as Structured Prompt for Agent
Please help me install this Agent Skill.
Skill: rails-query-optimization
Source: https://github.com/nekorush14/dotfiles/tree/main/configs/claude/skills/rails-query-optimization
Command: npx skills add https://github.com/nekorush14/dotfiles --skill rails-query-optimization

SYSTEM DOCUMENTATION & REQUIREMENTS

What problem does it solve?

This Skill optimizes ActiveRecord queries to prevent N+1 problems and improve performance.

Core Features & Use Cases

  • Eager Loading: Load associations upfront
  • Select Only Needed Columns: Minimize data transfer
  • Batch Processing: Use find_each for large datasets
  • Query Analysis: Use explain to understand queries
  • Avoid N+1: Preload associations

Quick Start

Analyze the Rails app to identify N+1 query patterns and apply eager loading strategies (e.g., replace loops fetching associations with includes).

Frequently Asked Questions about rails-query-optimization

High-intent search queries and answers about installing and using this skill.

FAQPage Schema
How do I fix N+1 query problems in Rails?

N+1 query problems occur when loops trigger separate database queries for each association. Fix them by using `includes` or `preload` to eager load associations upfront, reducing many queries to just two: one for the parent and one for all associated records.

What's the best way to optimize slow ActiveRecord queries?

Optimize ActiveRecord queries by eager loading associations with `includes`, selecting only needed columns with `select`, using `find_each` for batch processing large datasets, and running `explain` to analyze query execution plans and identify bottlenecks.

When should I use eager loading in Rails?

Use eager loading whenever you access associations inside loops or iterations. Eager loading prevents the database from executing one query per record and is essential for APIs, background jobs, and services processing multiple records to maintain consistent performance.

Can I improve Rails API performance without rewriting queries?

Yes. Start by analyzing queries with `explain` to identify N+1 patterns, then apply eager loading strategies like `includes` and column selection. Batch processing with `find_each` also reduces memory overhead and query load on large datasets.

Do I need to change my database schema to prevent N+1 queries?

No. N+1 prevention focuses on query strategy, not schema changes. Eager loading, preloading associations, and selecting specific columns solve N+1 problems entirely within ActiveRecord without altering your database structure.