debug:rails
Debug Rails issues systematically. Use when encountering ActiveRecord errors like RecordNotFound, routing issues, N+1 query problems detected by Bullet, asset pipeline issues, migration failures, gem conflicts, ActionController errors, CSRF token problems, or any Ruby on Rails application errors requiring diagnosis.
What this skill does
# Rails Debugging Guide
This skill provides a systematic approach to debugging Ruby on Rails applications, covering common error patterns, modern debugging tools, and proven troubleshooting techniques.
## Common Error Patterns
### 1. ActiveRecord::RecordNotFound
**Symptoms:** Rails fails to find a record in the database when using `find` or `find_by!` methods.
**Diagnosis:**
```ruby
# Check if record exists
rails console
> Model.exists?(id)
> Model.where(conditions).count
# Inspect the query being generated
> Model.where(conditions).to_sql
```
**Common Causes:**
- Record was deleted but reference still exists
- Incorrect ID passed from params
- Scopes filtering out the record
- Multi-tenancy issues (wrong tenant context)
**Solutions:**
```ruby
# Use find_by instead of find (returns nil instead of raising)
Model.find_by(id: params[:id])
# Handle gracefully in controller
def show
@record = Model.find_by(id: params[:id])
render_not_found unless @record
end
# Or rescue the exception
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
```
### 2. ActionController::RoutingError
**Symptoms:** 404 error - requested URL doesn't exist in the application.
**Diagnosis:**
```bash
# List all routes
rails routes
# Search for specific route
rails routes | grep resource_name
# Check route with specific path
rails routes -g path_pattern
```
**Common Causes:**
- Missing route definition in `config/routes.rb`
- Typo in URL or route helper
- Wrong HTTP verb
- Namespace/scope mismatch
- Engine routes not mounted
**Solutions:**
```ruby
# Verify route exists
Rails.application.routes.recognize_path('/your/path', method: :get)
# Add missing route
resources :users, only: [:show, :index]
# Check for namespace issues
namespace :api do
resources :users
end
```
### 3. NoMethodError (undefined method for nil:NilClass)
**Symptoms:** Calling a method on `nil` object.
**Diagnosis:**
```ruby
# Add debugging breakpoint
binding.break # Ruby 3.1+ / Rails 7+
debugger # Alternative
byebug # Legacy
# Check object state
puts object.inspect
Rails.logger.debug object.inspect
```
**Common Causes:**
- Database query returned no results
- Association not loaded
- Hash key doesn't exist
- Typo in variable/method name
**Solutions:**
```ruby
# Safe navigation operator
user&.profile&.name
# Null object pattern
user.profile || NullProfile.new
# Use presence
params[:key].presence || default_value
# Guard clauses
return unless user.present?
```
### 4. N+1 Query Problems
**Symptoms:** Slow page loads, excessive database queries in logs.
**Diagnosis:**
```ruby
# Check logs for repeated queries
tail -f log/development.log | grep SELECT
# Use Bullet gem for automatic detection
# Gemfile
gem 'bullet', group: :development
# config/environments/development.rb
config.after_initialize do
Bullet.enable = true
Bullet.alert = true
Bullet.rails_logger = true
end
```
**Common Causes:**
- Iterating over collection and accessing associations
- Missing `includes` or `preload`
- Calling methods that trigger queries in views
**Solutions:**
```ruby
# Eager loading with includes
User.includes(:posts, :comments).all
# Preload for large datasets
User.preload(:posts).find_each do |user|
user.posts.each { |post| ... }
end
# Use joins for filtering
User.joins(:posts).where(posts: { published: true })
# Counter cache for counts
belongs_to :user, counter_cache: true
```
### 5. Database Migration Failures
**Symptoms:** Migrations fail, schema out of sync, rollback errors.
**Diagnosis:**
```bash
# Check migration status
rails db:migrate:status
# View pending migrations
rails db:abort_if_pending_migrations
# Check current schema version
rails runner "puts ActiveRecord::Migrator.current_version"
```
**Common Causes:**
- Column/table already exists
- Foreign key constraint violations
- Data type incompatibility
- Missing index
- Irreversible migration
**Solutions:**
```bash
# Rollback and retry
rails db:rollback
rails db:migrate
# Reset database (development only!)
rails db:drop db:create db:migrate
# Fix stuck migration
rails runner "ActiveRecord::SchemaMigration.where(version: 'XXXXXX').delete_all"
# Use Strong Migrations gem for safety
gem 'strong_migrations'
```
### 6. ActionController::InvalidAuthenticityToken
**Symptoms:** CSRF token mismatch on POST/PUT/PATCH/DELETE requests.
**Diagnosis:**
```ruby
# Check if token is present in form
<%= csrf_meta_tags %>
# Verify token in request headers
request.headers['X-CSRF-Token']
```
**Common Causes:**
- Missing CSRF meta tags in layout
- JavaScript not sending token with AJAX
- Session expired
- Caching issues with forms
**Solutions:**
```erb
<!-- Add to layout head -->
<%= csrf_meta_tags %>
<!-- JavaScript AJAX setup -->
<script>
$.ajaxSetup({
headers: { 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }
});
</script>
```
```ruby
# For API endpoints, skip verification
skip_before_action :verify_authenticity_token, only: [:api_action]
# Or use null session
protect_from_forgery with: :null_session
```
### 7. ActionView::Template::Error
**Symptoms:** View rendering fails with template errors.
**Diagnosis:**
```ruby
# Error message shows file and line number
# Check the specific template mentioned
# Debug variables in view
<%= debug @variable %>
<%= @variable.inspect %>
# Use better_errors gem for interactive debugging
gem 'better_errors', group: :development
gem 'binding_of_caller', group: :development
```
**Common Causes:**
- Undefined variable in view
- Missing partial
- Syntax error in ERB
- Helper method not defined
- Nil object method call
**Solutions:**
```erb
<!-- Check for nil before rendering -->
<% if @user.present? %>
<%= @user.name %>
<% end %>
<!-- Use try for potentially nil objects -->
<%= @user.try(:name) %>
<!-- Safe navigation -->
<%= @user&.name %>
```
### 8. Asset Pipeline Issues
**Symptoms:** CSS/JS not loading, missing assets in production, Sprockets errors.
**Diagnosis:**
```bash
# Check asset paths
rails assets:precompile --trace
# View compiled assets
ls -la public/assets/
# Check manifest
cat public/assets/.sprockets-manifest*.json
```
**Common Causes:**
- Asset not in load path
- Missing precompile directive
- Incorrect asset helper usage
- Webpacker/esbuild configuration issues
**Solutions:**
```ruby
# Add to precompile list
# config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( custom.js custom.css )
# Use correct helpers
<%= javascript_include_tag 'application' %>
<%= stylesheet_link_tag 'application' %>
<%= image_tag 'logo.png' %>
# For Rails 7+ with import maps
<%= javascript_importmap_tags %>
```
### 9. Gem Conflicts and Bundler Issues
**Symptoms:** Bundle install fails, version conflicts, LoadError.
**Diagnosis:**
```bash
# Check gem versions
bundle info gem_name
# View dependency tree
bundle viz
# Check for outdated gems
bundle outdated
# Verify Bundler version
bundle --version
```
**Common Causes:**
- Incompatible gem versions
- Platform-specific gems
- Missing native extensions
- Lockfile out of sync
**Solutions:**
```bash
# Update specific gem
bundle update gem_name
# Clean reinstall
rm Gemfile.lock
bundle install
# Use specific version
gem 'problematic_gem', '~> 1.0'
# Platform constraints
gem 'specific_gem', platforms: :ruby
```
### 10. NameError (Uninitialized Constant)
**Symptoms:** Ruby can't find class, module, or constant.
**Diagnosis:**
```ruby
# Check if constant is defined
defined?(MyClass)
# View autoload paths
puts ActiveSupport::Dependencies.autoload_paths
# Check zeitwerk loader
Rails.autoloaders.main.dirs
```
**Common Causes:**
- File not in autoload path
- Typo in class/module name
- Wrong file naming convention
- Circular dependency
- Missing require statement
**Solutions:**
```ruby
# Ensure file naming matches class name
# app/models/user_profile.rb -> class UserProfile
# Add to autoload paths if needed
# config/application.rb
config.autoRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.