Blog

Claude Code for Rails: Best workflow and safety practices

Goon Nguyen•Claude Code Guides••16 min read

Claude Code for Ruby on Rails: Practical workflow, best use cases and safety tips

Claude Code speeds up Rails development, but faster generation matters only if changes are safe and clear. While Rails conventions simplify navigation, they don't block auth gaps or risky migrations. This guide shows how to delegate tasks, prepare your repo, and apply the Plan → Change → Verify workflow without giving up engineering control.

Claude Code for Rails: Best workflow and safety practices

Why Claude Code works well with Ruby on Rails

Claude Code can work effectively with Ruby on Rails because conventional directories help it locate related implementation and test files. That structure supports repository-aware coding, but it does not reveal every business rule. Useful results still depend on inspecting the application, supplying project context, and reviewing behavior against explicit requirements.

Rails gives the agent a predictable repository map

The Rails Guides describe convention over configuration: Shared defaults reduce the number of decisions applications must specify. For a coding agent, those conventions offer a starting map.

app/models/ → persistence, associations, validations
app/controllers/ → request handling
app/views/ → rendered interfaces
app/jobs/ → background processing
db/migrate/ → database changes
spec/ OR test/ → the repository’s existing test suite

An account-preference change might involve the account model, settings controller, authorization policy, notification job, and corresponding tests. Predictable placement helps identify these connections; Claude does not automatically read or understand the entire repository.

Claude Code for Rails: Best workflow and safety practices

Convention helps, but it is not a substitute for context

Ruby on Rails conventions leave important questions unanswered:

  • Custom service objects or form objects.
  • Authorization libraries and tenant boundaries.
  • Callbacks and metaprogramming.
  • Rails engines and undocumented legacy patterns.
  • Background job and frontend conventions.

A familiar directory structure does not establish business correctness. Explain these project-specific decisions in a concise briefing before requesting implementation.

What Rails tasks should you delegate to Claude Code?

Delegate work with bounded scope and observable outcomes. Evaluate reversibility, blast radius, sensitive-data access, and test maturity, rather than assuming a task is safe because it sounds routine. Blast radius means how much of the application a mistake could affect.

Rails task and risk matrix

Typical risk varies by repository, deployment environment, and change scope.

Task

Potential value

Typical risk

Context required

Required review

Test generation or expansion

Draft RSpec or Minitest cases

Low–medium; weak assertions

Behavior contract, fixtures

Inspect assertions and failure paths

Views and translations

Reduce repetitive edits

Low–medium

Design, accessibility, locales

Rendered behavior and escaping

Backtrace diagnosis

Accelerate backtrace debugging

Low for sanitized analysis; fix varies

Redacted trace, reproduction

Validate diagnosis before edits

Validations and associations

Draft conventional changes

Medium

Data rules, existing records

Compatibility and constraints

Controllers, jobs, and service objects

Implement bounded behavior

Medium–high

Policies, retries, conventions

Authorization and side effects

Business-logic refactoring

Support AI-assisted refactoring

Medium–high

Invariants, callers, tests

Behavior preservation

Dependency upgrades

Analyze changes, draft patches

Medium–high; major Rails upgrades high

Compatibility, release notes

Integration and deployment checks

Production data migrations

Draft a migration plan

High

Data volume, locks, recovery

Database and operational approval

Authentication, authorization, and payments

Explore options, draft tests

High

Security and financial rules

Qualified domain review

Destructive database or production operations

Prepare a human-run checklist

Critical

Backups, targets, authorization

Human-controlled execution

Sanitize debugging material before sharing it. A backtrace can contain customer identifiers, request parameters, or credentials. Permission to analyze a failure is not permission to execute a fix.

Tasks that should remain human-led

Humans retain ownership of domain decisions, authorization boundaries, architectural changes, irreversible operations, deployment, merge approval, and final acceptance.

Claude can draft alternatives and support test-first development. It cannot independently establish whether its tests represent the correct product behavior. Delegating implementation is not delegating accountability.

How to set up Claude Code for an existing Rails project

Start with a known baseline and a restricted development environment. Claude Code should already be installed and authenticated using the official Claude Code setup documentation appropriate to your installed version.

Start with a safe repository baseline

  1. Confirm local boot: Resolve environment problems before assigning feature work.
  2. Run relevant baseline tests: Record pre-existing failures and missing services.
  3. Inspect Git status: Commit, safely stash, or separate unrelated changes; do not delete them.
  4. Create a task branch: Use an optional worktree for a separate working directory.
  5. Start Claude Code at the repository root: Confirm which application it should inspect.
  6. Select Plan Mode and restricted permissions: Check the installed version’s documented controls.
  7. Request inspection and a plan before edits: Require unknowns and proposed verification.

Plan Mode is a planning aid, not a security sandbox. Permissions, environment isolation, credential restrictions, and human approval are separate controls.

Create a minimal Rails CLAUDE.md

The official Claude Code memory documentation describes CLAUDE.md as a way to supply project instructions. Keep it factual and short.

# Project briefing

## Stack
- Ruby: <version>; Rails: <version>
- Database: <engine/version>
- Tests: <RSpec or Minitest>
- Background jobs: <adapter and conventions>
- Authentication: <implementation>
- Authorization/tenancy: <implementation and boundaries>

## Approved local commands
- Focused tests: <project-specific command>
- Broader tests: <project-specific command>
- Lint/security checks: <configured commands>

## Architecture
- Inspect <db/schema.rb OR db/structure.sql>.
- Follow nearby controller, model, job, and test patterns.
- Business logic belongs in <existing project convention>.

## Safety
- Inspect and propose a plan before editing.
- Stop when authorization or tenant behavior is unclear.
- Request approval before adding gems or changing deployment.
- No production access or destructive operations.
- Never include credentials or customer data in output.

## Definition of done
- Acceptance criteria and denied paths covered.
- Diff reviewed; migration implications documented.
- Report checks separately: passed, failed, not run.
- Record assumptions, remaining risks, and recovery notes.

Replace placeholders with repository-approved values. Do not impose service objects or other abstractions merely to make the application easier for an agent to navigate. These instructions guide behavior; they do not technically block secret access.

Move reusable instructions into dcoped tules

Keep the root briefing short. Organize longer testing, Rails, frontend, and security guidance under .claude/rules/, following the official rules documentation.

Use documented path scoping where supported. A directory name alone does not make instructions conditionally load. Review rules alongside application changes so outdated guidance does not become repeated error.

The plan, change, verify workflow for rails development

A Claude Code Rails workflow should turn a bounded ticket into an approved plan, a reviewable change, and explicit verification evidence. Plan establishes behavior and scope; Change implements only that scope; Verify checks the result. A human owns the approval gates, unresolved assumptions, and final decision to merge the work.

Claude Code for Rails: Best workflow and safety practices

The following illustrative workflow is untested. It demonstrates review artifacts, not a recorded implementation or measured productivity result.

Step 1 - Define the task and acceptance criteria

Specify exactly which notifications the preference controls.

Goal:
Add an account-level preference for optional weekly summary emails.

Acceptance:
- Existing accounts retain their current delivery behavior.
- Authorized account admins can update their own account only.
- Unauthorized and cross-account updates are rejected.
- Invalid input follows the existing application error contract.
- Summary delivery respects the saved preference.
- Security and mandatory transactional emails are unchanged.
- Relevant allowed, denied, and delivery tests are required.

Compatibility:
Use existing settings, authorization, and test conventions.
Identify migration and deployment implications.

Exclusions:
No new dependency, unrelated refactor, or deployment change.

Planning only:
Inspect relevant files, identify unknowns, and propose a plan.
Do not edit yet.

Existing behavior must be established through inspection. Do not assume every account currently receives a summary.

Step 2 - Ask Claude to inspect before it designs

Request relevant file paths and explanations covering:

  • Routes and request handling.
  • db/schema.rb or db/structure.sql.
  • Account models and notification jobs.
  • Policies or other authorization code.
  • Forms or serializers.
  • Existing tests and fixture or factory patterns.

Require the plan to separate findings from assumptions. If tenant selection or authorization behavior remains unclear, stop for clarification.

Step 3 - Review the plan before allowing edits

Check proposed files, schema assumptions, callbacks, dependencies, and new abstractions. Review deployment order, database locking, and recovery before accepting a migration.

For this demonstration, consider a proposal that checks administrator status but loads an account through an unrestricted identifier. Reject it: Role membership alone does not prove access to that account. Require the existing tenant-scoped lookup and a cross-account rejection test.

This is an illustrative review decision, not a recorded agent failure.

A reversible migration can still block traffic or break compatibility during deployment. Split the plan when database changes and application rollout require different operational steps.

Step 4 - Implement one reviewable slice at a time

Approve a coherent behavioral change, not an arbitrary line-count limit. Keep the preference separate from cleanup, dependency upgrades, and architectural redesign.

Request a concise summary after each slice. Checkpoint stable work according to repository policy. If inspection reveals new requirements, return to planning rather than allowing scope to expand silently.

Step 5 - Run focused tests first

Use the existing RSpec or Minitest setup. Start with the nearest request, model, and notification-job tests.

Cover permitted updates, denied updates, cross-account access, invalid input, and delivery behavior. Diagnose failures before repeated edits. Require explicit approval before changing existing assertions; making a test pass by weakening it is not verification.

Step 6 - Expand verification

Run broader tests and required CI (continuous integration) checks, followed by configured linting and formatting tools. Include Brakeman where configured, schema review, migration review, and relevant manual acceptance.

Record checks blocked by unavailable services or credentials as not run, not passed. The next section explains what each verification layer can establish.

Step 7 - Review the Diff and prepare the pull request

Inspect the entire diff, including tests. Check authorization, tenant isolation, callbacks, job side effects, query behavior, configuration, dependencies and unrelated edits.

The pull request should document purpose, executed checks, migration notes, assumptions, remaining risks, and rollback or recovery considerations.

Phase

Primary action

Exit condition

Plan

Inspect files and define scope

Human-approved plan with unknowns resolved or explicitly deferred

Change

Implement a bounded behavior

Coherent diff ready for verification

Verify

Run checks and document review evidence

Review-ready PR; merge still requires repository policy, CI, and authorized approval

How to test and review Claude-generated Rails code safely

Passing checks can coexist with incorrect business behavior. Claude-generated Rails code may also differ between attempts, so acceptance must depend on the actual diff and evidence—not confidence in a previous response.

Use four verification layers

Layer

Evidence

Coverage boundary

Focused behavior

Request, model, job, or system tests

RSpec and Minitest validate assertions that humans must inspect

Repository quality

Broader tests, CI, configured RuboCop rules

Tests cover exercised behavior; RuboCop does not prove architectural correctness

Security and data safety

Brakeman, authorization tests, migration review

Static analysis does not prove tenant isolation or deployment safety

Human acceptance

Product walkthrough and diff review

Evaluates business behavior, maintainability, and unintended scope

For the notification preference, a successful update test proves little about cross-account access unless that boundary is separately exercised.

Claude Code for Rails: Best workflow and safety practices

Rails-specific review checklist

Ask these ten questions before acceptance:

  1. Does authorization protect the correct account, not merely a permitted role?
  2. Can callbacks trigger unexpected emails, writes, or external actions?
  3. Does the change introduce N+1 queries—repeated database queries for individual records?
  4. Could migrations cause locks, or require a specific deployment order?
  5. Is rollback or recovery practical after data changes?
  6. Are job retries safe and idempotent, meaning repetition avoids unintended duplicate effects?
  7. Are validations and database constraints appropriate to the invariant?
  8. Do routes, permitted parameters, or serializers expose unintended behavior?
  9. Could prompts, logs, or output disclose sensitive information?
  10. Were existing tests weakened, skipped, or rewritten to match faulty behavior?

Rails security guidance is a baseline; application-specific trust boundaries still require direct review.

Permission and command guardrails

Action

Guardrail

Read files

Permit necessary context; restrict secrets and sensitive data separately

Edit files

Limit changes to approved scope and inspect the diff

Install dependencies

Require explicit approval

Run tests or linters

Use approved commands in a safe environment; they can execute code, write files, or contact services

Modify schema

Review the change and confirm the target database

Access credentials

Keep production credentials unavailable

Use network or MCP tools

Restrict tools, destinations, credentials, and actions

Deploy

Keep under authorized human control

Destructive operations

Exclude from routine autonomous execution

MCP (Model Context Protocol) connects agents with external tools and context. Connectivity does not establish that access is safe.

Report “Brakeman completed with these findings,” not “security passed.” Scanner output is one input to acceptance.

Using Git worktrees and measuring real productivity

Git worktrees can help separate concurrent tasks, but they do not solve runtime isolation or establish productivity. Evaluate both the working arrangement and the total delivery effort.

When Git worktrees are useful

Use one task, branch, and worktree per session when parallel work would otherwise interfere. Avoid overlapping edits and review each branch before integration.

The official Git worktree documentation describes multiple working trees associated with one repository. They separate working directories and branch checkout state, not complete environments.

Worktrees do not isolate databases, Redis or caches, credentials, external APIs, shared filesystem resources, or all Git metadata. Assign separate ports and runtime resources where needed. A migration from one worktree may still affect another session’s database.

Claude Code for Rails: Best workflow and safety practices

Run a two-week productivity evaluation

Compare similar tasks and complexity. Record the model, Claude Code version, repository context, and evaluation period.

Metric

Record

Time to review-ready PR

Elapsed time from task start to documented readiness

Human review time

Active reviewer minutes

Corrective prompts

Number and reason for interventions

Rework

Active correction effort and cause

Introduced test failures

New failures attributable to the change

Escaped defects

Defects discovered after acceptance

Subscription or usage cost

Applicable subscription allocation and usage charges

Developer focus and satisfaction

Consistent short survey with comments

Separate elapsed delivery time from human effort. Use nonoverlapping categories when totaling implementation, review, and rework; do not count the same minutes twice.

More rework is not automatically a failed pilot if total effort falls without harming quality. Conversely, faster generation may create expensive review.

Treat two weeks as an initial signal, not proof of long-term return. Continue monitoring escaped defects. Generated lines of code are not a meaningful primary measure of developer productivity.

From individual prompts to a repeatable Rails agent workflow

Standardization becomes valuable when maintaining instructions and coordinating reviews becomes recurring work. Additional tooling is optional; it should address an observed coordination problem.

When a manual Claude Code workflow is enough

A manual approach may be sufficient when you have:

  • One primary repository owner.
  • Limited repeated task types.
  • Stable project instructions.
  • Consistent testing and review habits.
  • Little need to share configurations.

A small application is not necessarily low-risk. Sensitive data and governance requirements matter independently of team size.

When atandardization becomes necessary

Look for observable friction: Multiple repositories or contractors, repeatedly rebuilt prompts, stale instructions, inconsistent verification, configuration drift, or unclear tool access and review ownership.

First standardize the underlying process. Packaging an unclear workflow only makes its inconsistencies easier to repeat.

Illustrative workflow - no execution or performance results

Evidence field

Record for the pilot

Repository and Rails version

Sanitized repository identifier and exact version

Claude Code version and model

Exact versions used

Task

Account-level optional weekly summary preference

Steps standardized or automated

Planning brief, scoped task handoff, verification checklist

Human checkpoints

Plan approval, migration review, final acceptance

Review-ready time and method

Not measured; define start, stop, and waiting-time treatment

Corrections

Record actual rejected suggestions and resulting changes

Tests and security checks run

None in this illustration; attach real command results

Known limitations

No runtime validation or demonstrated productivity improvement

A proposed process is not proof of work. Before expanding adoption, collect the approved plan, diff, check output, corrections, and PR summary from a real task.

Frequently asked questions

What are the main benefits of using Claude Code with Ruby on Rails?

Claude Code leverages Rails’ predictable directory conventions to locate files efficiently and uses Ruby’s concise syntax for high token efficiency. This allows the agent to generate boilerplate, migrations, and test coverage accurately, significantly accelerating development cycles while maintaining standard architectural patterns.

How does "Plan Mode" improve safety in Rails development?

Plan Mode gives you an approval gate: inspect the proposal, scope, and unknowns before implementation begins. It is a planning aid, not a sandbox-permissions, environment isolation, and credential restrictions remain separate controls.

Should I delegate every Rails task to Claude Code?

No. Delegate bounded tasks like test generation, view updates, and backtrace diagnosis. High-risk operations—such as complex authorization changes, destructive database operations, or core architectural decisions—should always remain human-led to ensure business logic correctness and data integrity.

How can I isolate agent work from my primary Rails branch?

Worktrees give each task its own working directory and branch checkout. They do not isolate databases, caches, credentials, or external services — a migration run from one worktree can still affect another session's database, so assign separate ports and runtime resources.

What is the purpose of a CLAUDE.md project briefing?

A CLAUDE.md file serves as a project-specific instruction set. It defines your repository’s conventions—such as recording your actual stack, approved commands, existing conventions, and safety boundaries, or identifying approved commands—ensuring the agent aligns its output with your team's established Rails development standards.

Are automated Rails tests sufficient for verifying agent code?

Not entirely. While passing RSpec or Minitest suites is critical, tests only validate the specific assertions written. Human review is required to assess broader implications, such as unintended side effects, security vulnerabilities, query performance, and whether the code effectively meets the defined business requirements.

Can AgentKit help standardize my team's Rails workflows?

It can help where coordination is the actual problem. AgentKit Engineer is a licensed kit installed into your coding agent - reusable skills, specialized subagents, pre-tool approval hooks, and configuration management across repositories.

It is not a hosted platform, and it does not enforce correctness: review, CI, and human approval remain unchanged. Standardize the underlying process first. Disclosure: AgentKit is our product.

Read more:

Conclusion

An effective Claude Code Rails workflow relies on Plan → Change → Verify, combining Rails conventions with clear project context to deliver safe, reviewable changes. Start with a low-risk task in development, set clear criteria, inspect every diff, and keep final approval under human control.

Once proven, you can evaluate tools like AgentKit Engineer to standardize the process across repositories based on real, documented results.

Share this article