Claude
Skills
Sign in
Back

debug:rails

Included with Lifetime
$97 forever

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.

Code Review

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.auto

Related in Code Review