RailsClaude
Chat with Claude AI directly inside your Rails console, with automatic Rails context.
RailsClaude drops an AI assistant into rails c that already knows your app's models, environment, and Ruby/Rails versions. Ask questions in plain English, get back ActiveRecord queries, debugging help, and code you can auto-execute — all without leaving the REPL.
Installation
Add the gem to your development group:
group :development do
gem "rails_claude"
endThen run:
bundle installRequirements
- Ruby 3.0+
- Rails 6.0+
- An Anthropic API key
Configuration
Set your API key as an environment variable:
export ANTHROPIC_API_KEY=sk-ant-...Optional Configuration
Create an initializer at config/initializers/rails_claude.rb to customize behavior:
RailsClaude.configure do |config|
config.api_key = ENV["ANTHROPIC_API_KEY"] # default
config.model = "claude-opus-4-6" # default
config.max_tokens = 1024 # default
config.safe_mode = Rails.env.production? # default
config.system_prompt = "Custom system prompt..." # auto-generated by default
end| Option | Default | Description |
|---|---|---|
api_key |
ENV["ANTHROPIC_API_KEY"] |
Your Anthropic API key |
model |
"claude-opus-4-6" |
Claude model to use for requests |
max_tokens |
1024 |
Maximum tokens per response |
safe_mode |
true in production, false otherwise |
Wrap code execution in a rolled-back transaction |
system_prompt |
Auto-generated | System prompt with Rails context (see below) |
Auto-generated System Prompt
By default, RailsClaude builds a system prompt that includes:
- Your application name
- All detected model classes (ApplicationRecord descendants)
- Current Rails environment
- Ruby and Rails versions
This gives Claude immediate awareness of your app's structure without any manual setup.
Usage
When you start rails c, RailsClaude loads automatically and prints available commands:
✦ RailsClaude ready. (safe mode)
claude "question" — chat
claude_run! "question" — chat + auto-eval code
claude_load_model User — load a model for analysis
claude_load_file "path/to/f" — load any file for analysis
claude_safe_mode! / claude_unsafe_mode!
claude_history / claude_reset!
claude — Ask a Question
Send a message to Claude and get a response. Conversation history is maintained across calls, so follow-up questions work naturally.
claude "find users who signed up in the last 7 days"
claude "now filter those to only verified accounts"
claude "what indexes would speed that query up?"
claude_run! — Ask and Auto-Execute Code
Like claude, but automatically extracts Ruby code blocks from Claude's response, executes them in the console, and feeds the result back. Runs up to 3 iterations by default (configurable via max_iterations).
claude_run! "how many orders are in pending state?"
# Claude responds with: Order.where(status: "pending").count
# ⚡ Running: Order.where(status: "pending").count
# ⮕ Result: 42
claude_run! "show me the 5 most recent users", max_iterations: 1Code is displayed in yellow before execution, and results appear in green. If the executed code raises an error, the error is captured and sent back to Claude for debugging context.
claude_load_model — Load a Model for Analysis
Inject a model's full source code into the conversation so Claude can analyze it.
claude_load_model User
claude_load_model "Post" # string names work too
claude "what validations does this model have?"
claude "find any N+1 query risks in the associations"The gem finds the source file via source_location on the model's instance methods, falling back to app/models/<name>.rb.
claude_load_file — Load Any File for Analysis
Inject any file in your project into the conversation context.
claude_load_file "app/services/billing_service.rb"
claude_load_file "config/routes.rb"
claude "walk me through the billing flow"Paths are resolved relative to Rails.root.
claude_history — View Conversation History
Display all messages in the current session. User messages appear in cyan, Claude's responses in magenta.
claude_history
claude_safe_mode! / claude_unsafe_mode! — Toggle Safe Mode
Switch between safe and unrestricted modes during a session without restarting the console.
claude_unsafe_mode!
# ⚠ Safe mode disabled — code will execute with full write access.
claude_run! "create a test user" # this will persist
claude_safe_mode!
# 🔒 Safe mode enabled — code runs in rolled-back transactions.claude_safe_mode! also accepts a boolean: claude_safe_mode!(false) is equivalent to claude_unsafe_mode!.
claude_reset! — Clear History
Start a fresh conversation. Clears all message history while keeping your configuration.
claude_reset!
claude_session — Access the Session Object
For advanced usage, access the underlying RailsClaude::Session instance directly.
session = claude_session
session.history # inspect raw conversation historyExamples
Exploring Data
claude_run! "how many users signed up this month?"
claude_run! "show me the top 10 by order count"
claude_run! "what's the average order value for those users?"Debugging a Model
claude_load_model Order
claude "what happens when status transitions from pending to fulfilled?"
claude "are there any callbacks that could cause side effects?"Analyzing a Service
claude_load_file "app/services/payment_service.rb"
claude_load_file "app/models/payment.rb"
claude "what error cases does the payment service handle?"
claude_run! "show me an example of calling the main method"Multi-Step Investigation
claude "are there any orders stuck in processing for more than 24 hours?"
claude_run! "find them"
claude_run! "show me the associated user for the oldest one"
claude "what should I check to debug this?"Safe Mode
Safe mode prevents claude_run! from making any persistent changes to your database. When enabled, all auto-executed code runs inside a database transaction that is always rolled back after the result is captured. Read queries work normally; writes are silently undone.
Safe mode is on by default in production and off in development/test. You'll see the current mode in the startup banner:
✦ RailsClaude ready. (safe mode)
or:
✦ RailsClaude ready. (unrestricted)
The system prompt also instructs Claude to only generate read-only code when safe mode is active.
Overriding Safe Mode
# Force safe mode on in development
RailsClaude.configure do |config|
config.safe_mode = true
end
# Disable safe mode in production (use with caution)
RailsClaude.configure do |config|
config.safe_mode = false
endWhat Safe Mode Protects Against
-
INSERT,UPDATE,DELETEstatements — rolled back after execution -
ActiveRecordcreate/update/destroy calls — rolled back after execution - Claude is prompted to avoid generating destructive code entirely
What Safe Mode Does Not Protect Against
- Non-database side effects (file I/O, HTTP requests, system commands)
- Schema changes (
ALTER TABLE, migrations) — these may auto-commit depending on your database
For full isolation in production, consider restricting the database user's permissions as well.
How It Works
RailsClaude uses a Rails Railtie to hook into console startup. When rails c loads:
- Eager loads the application to discover all model classes
- Creates a session with an Anthropic API client and auto-generated system prompt
-
Defines helper methods (
claude,claude_run!, etc.) onObjectso they're available as top-level console commands
Each call to claude or claude_run! sends the full conversation history to the Claude API, maintaining context across turns. claude_run! additionally extracts fenced code blocks (```ruby or ```) from responses, evaluates them in the console context, and loops the result back for up to max_iterations rounds.
License
The gem is available as open source under the terms of the MIT License.