Claude Code for Ruby on Rails Development: The Complete 2026 Guide
Set up Claude Code for Ruby on Rails — CLAUDE.md structure, RSpec/Minitest workflows, migrations, N+1 debugging, and why Rails is the most token-efficient framework for AI pair programming.
Claude Code for Ruby on Rails Development: The Complete 2026 Guide
Rails has always been a framework built on a bet: that convention beats configuration. In 2026, that bet is paying off in a way David Heinemeier Hansson probably didn't anticipate — Rails turns out to be one of the best-suited frameworks for AI coding agents. A RubyKaigi 2025 analysis benchmarking 18 languages found Ruby ranked #1 in token efficiency with Claude Code, at roughly $0.36 per completed task. Y Combinator CEO Garry Tan has called Rails' convention-over-configuration approach "LLM catnip," because the framework's predictable file structure means Claude's first guess about where code lives is usually correct.
If you're running Claude Code against a Rails app and still treating it like a generic autocomplete tool, you're leaving most of that efficiency advantage on the table. This guide covers the setup, the CLAUDE.md structure that actually works for Rails, and the day-to-day workflows — migrations, N+1 debugging, RSpec/Minitest generation, and legacy modernization — that make Claude Code feel like it understands your app/ directory instead of guessing at it.
Why Rails and Claude Code Are a Natural Fit
Most frameworks make an AI agent work to understand where things live. Rails does the opposite. A controller action almost always has a matching view, a matching route entry, and a matching model — all in predictable directories following the same naming pattern. That predictability compounds:
app/models/order.rbalmost certainly has an associatedspec/models/order_spec.rbortest/models/order_test.rb.db/migrate/timestamps give Claude an implicit changelog of your schema's evolution, without you explaining it.config/routes.rbis a single source of truth for every endpoint in the app — no scattered route decorators or annotation-based routing to reconcile.
Real-world usage backs this up. Developers running Claude Code against production Rails apps report debugging sessions that used to take 45 minutes — tracing a backtrace through a service object, a background job, and a model callback — dropping to under 10 minutes, largely because Claude can read a stack trace and correctly infer the full call path on the first try.
None of that means Claude Code works well in Rails by default, though. The gap between "decent Rails code" and "code that matches your team's actual conventions" is almost entirely closed by one file: CLAUDE.md.
Writing a CLAUDE.md That Actually Helps in a Rails Repo
Rails' flexibility is a double-edged sword for AI agents. The framework will happily let you put business logic in a fat model, a service object, a concern, or a background job — and without an anchor, Claude will default to whatever pattern shows up most in its training data, not what your team actually uses.
A focused CLAUDE.md at your project root fixes this in one pass, because Claude Code reads it automatically at the start of every session:
markdown# Project: [App Name]
## Stack
- Rails 7.2, Ruby 3.3
- RSpec for testing (not Minitest) — use `let`, not instance variables
- RuboCop for linting — run `bundle exec rubocop -a` before finishing
- Sidekiq for background jobs, Hotwire (Turbo + Stimulus) for the frontend
## Conventions
- Business logic lives in app/services, not fat models or fat controllers
- All external API calls go through app/clients, never inline HTTP calls
- Feature specs live in spec/requests, mirroring routes.rb structure
- Use `frozen_string_literal: true` on every new file
## Database
- Managed via db/migrate/ — never edit a migration that's already run in staging
- Foreign keys and NOT NULL constraints are mandatory on new columns
## Do not
- Add gems to the Gemfile without asking first
- Touch app/models/concerns/tenant_scoped.rb without flagging it explicitlyTwo things make this more valuable in Rails specifically than in most other stacks. First, Rails' "many ways to do one thing" flexibility means style drift compounds fast across a codebase without an anchor. Second, RSpec vs. Minitest is a binary choice with almost no middle ground — get it wrong once and Claude will generate a test file your suite can't even load.
Core Workflows That Actually Save Time
1. Migrations that match your schema history
Rails' db/migrate/ directory is effectively a changelog Claude can read directly, so point it there instead of describing your schema from scratch:
Add a `cancelled_at` nullable datetime to the subscriptions table.
Follow the same migration style as the last three files in
db/migrate/ — include a foreign key index if there's a matching
belongs_to.Because Claude can read your actual schema.rb or structure.sql, it won't propose a column name that collides with an existing one, and it will match whether your team adds explicit indexes on every migration or relies on Rails' defaults.
2. Debugging N+1 queries and slow endpoints
N+1 queries are Rails' most common performance bug, and they're also one of the easiest things for Claude Code to catch — if you give it something to run:
The /api/subscriptions endpoint is slow. Run the request in a Rails
console with Bullet enabled (or check the logs for repeated SELECT
patterns) and suggest eager-loading fixes for SubscriptionSerializer.Because Claude Code can execute shell commands and read rails console or bin/rails runner output directly, it can confirm a query count before proposing includes(:plan, :payment_method) rather than guessing based on which associations exist.
3. Generating specs that match your suite's shape
RSpec conventions vary enormously between teams — let vs. instance variables, shared examples, request specs vs. controller specs. Anchor every generation request to a real file:
Write a request spec for POST /subscriptions/:id/cancel,
matching the structure and factory usage in
spec/requests/subscriptions_spec.rbThis single habit — pointing at an existing file instead of describing style in prose — is the highest-leverage prompt pattern in Rails work, because Rails apps accumulate house conventions (factory naming, shared context blocks, VCR cassette patterns) that are nearly impossible to fully describe but trivial to demonstrate.
4. Legacy Rails modernization
Old Rails apps — think Rails 4.x/5.x callbacks-everywhere, or pre-service-object codebases — benefit from planning before Claude touches anything:
/plan Extract the subscription cancellation logic out of
Subscription#cancel! into a SubscriptionCancellationService.
Keep the public method signature identical so nothing calling
`.cancel!` breaks.Planning first matters more in legacy Rails than almost anywhere else, because before_save and after_commit callbacks hide side effects that only surface once you try to move the logic somewhere else. A plan step forces Claude to enumerate those side effects before it starts moving code.
Claude Code vs. Generic AI Autocomplete for Rails
| Capability | Generic AI autocomplete | Claude Code in a Rails repo |
|---|---|---|
| Infers file location from convention | Sometimes | Reliably — Rails' structure is close to deterministic |
| Reads actual schema/migration history | No — pattern-matches on model names | Yes — reads db/schema.rb and db/migrate/ directly |
| Executes code to verify a fix | No | Yes — via rails console, rails runner, Bash tool |
| Runs your real test suite before calling done | No | Yes — RSpec/Minitest in-session |
| Multi-file refactor planning | Limited | Yes — plan mode surfaces callback side effects first |
| Token cost per task (RubyKaigi 2025 benchmark) | Varies, framework-agnostic | ~$0.36/task — #1 of 18 languages tested |
Handling Multi-Tenant and Service-Heavy Rails Apps
Larger Rails codebases — multi-tenant SaaS, or apps leaning on Pundit for authorization, Sidekiq for background processing, or a heavy service-object layer — need one extra piece of context up front: how isolation and authorization actually work, because Claude can't infer either from file structure alone.
This app uses row-level multi-tenancy via an `account_id` column
on every tenant-scoped table, enforced by `default_scope` in
ApplicationRecord's TenantScoped concern. When adding new models,
always include TenantScoped and never write raw SQL or `.unscoped`
queries that bypass it.Skipping this is the most common way AI-assisted Rails work introduces a real bug: a new model or a raw ActiveRecord::Base.connection.execute call that quietly skips tenant scoping. Treat this instruction the same way you'd treat a mandatory code review checklist item, because functionally that's what it is.
Running the Test Suite Before You Trust the Output
Claude Code can run shell commands directly inside a session, so the loop for any non-trivial change should end with the test suite running — not with you eyeballing the diff:
bashbundle exec rubocop -a
bundle exec rspecAsk Claude to run both and paste the actual output back into the conversation, rather than describing what it changed. For migration-heavy changes, also ask it to run the migration against a scratch database and check db/schema.rb diffed cleanly — a green test suite doesn't always catch a migration that silently drops data on a column type change.
Common Mistakes to Avoid
- Skipping CLAUDE.md and relying on file-reading alone. Claude Code without a style anchor will write functionally correct Rails code that doesn't match your team's service-object-vs-fat-model conventions, RSpec-vs-Minitest choice, or callback philosophy.
- Letting Claude touch migrations already run in staging or production without a plan step. Column drops, type changes, and renames should always go through
/planfirst. - Not anchoring test generation to an existing spec file. Rails' testing ecosystem has too many valid conventions to describe in prose — show, don't tell.
- Omitting tenant-scoping or authorization rules from CLAUDE.md. This is the single highest-impact gap in multi-tenant Rails apps, and it's a one-paragraph fix.
- Not running the real test suite in-session. Claude Code has shell access — use it. A described fix is not a verified fix.
Key Takeaways
- Rails' convention-over-configuration design makes it one of the most token-efficient frameworks for Claude Code, benchmarked at #1 of 18 languages tested by RubyKaigi 2025 analysis.
- A focused CLAUDE.md documenting your testing framework, service-layer conventions, and tenant-scoping rules closes most of the gap between "decent Rails code" and "code that matches your team."
- Anchor migrations, N+1 debugging, and spec generation to real files in your repo — Rails' predictable structure means Claude can read schema and route history directly instead of guessing.
- Use plan mode before touching legacy callback-heavy code or any migration that's already run in a shared environment.
Next Steps
Studying for a Claude certification while you build? AI for Anything's Claude Certified Architect practice tests cover the same tool-use and multi-file reasoning patterns that show up in real Rails workflows like these — start with a free sample question set before you sit the real exam.
Rohit Mote
Founder, AI for Anything
Rohit Mote is the founder of AI for Anything and builds AI-powered products full-time across the Infinite Products Machine portfolio. Every guide is grounded in hands-on daily use of Claude, Claude Code, and the broader AI tool ecosystem in production systems.
How we create and review our guides →