Fix ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "orders.status" does not exist in Rails
This error occurs when a scope or query references a database column that does not exist. It often happens when scopes reference columns from a different table without a proper join, or when a migration adding the column was not run. Verify the column exists in the database schema and add necessary joins to your scope chain.
Reading the Stack Trace
Here's what each line means:
- activerecord (7.1.3) lib/active_record/connection_adapters/postgresql_adapter.rb:672:in `exec_params': PostgreSQL rejects the query because it references a column that does not exist in the orders table.
- app/models/user.rb:12:in `active_customers': The active_customers scope references orders.status without joining the orders table.
- app/controllers/admin/users_controller.rb:6:in `index': The admin controller calls the broken scope chain.
Common Causes
1. Scope references unjoined table column
A scope on User references a column from Orders without joining the table.
class User < ApplicationRecord
scope :active_customers, -> { where('orders.status = ?', 'completed') }
# Missing: .joins(:orders)
end
2. Chained scopes with conflicting conditions
Two scopes when chained produce an invalid SQL query.
class Product < ApplicationRecord
scope :available, -> { where(in_stock: true) }
scope :by_category, ->(cat) { where(category_id: cat) }
scope :with_reviews, -> { where('reviews.rating > 3') } # No join
end
Product.available.with_reviews # Fails
3. Column removed in migration
A scope references a column that was removed in a migration.
# Migration removed 'status' column from orders
# But scope still references it
scope :pending, -> { where(status: 'pending') }
The Fix
Add .joins(:orders) to properly join the orders table before filtering on its columns. Use the hash syntax for where conditions and add .distinct to prevent duplicate users from the join.
class User < ApplicationRecord
scope :active_customers, -> { where('orders.status = ?', 'completed') }
end
class User < ApplicationRecord
scope :active_customers, -> {
joins(:orders).where(orders: { status: 'completed' }).distinct
}
end
Testing the Fix
require 'rails_helper'
RSpec.describe User, type: :model do
describe '.active_customers' do
it 'returns users with completed orders' do
user_with_order = create(:user)
create(:order, user: user_with_order, status: 'completed')
user_without_order = create(:user)
expect(User.active_customers).to include(user_with_order)
expect(User.active_customers).not_to include(user_without_order)
end
it 'does not return duplicates' do
user = create(:user)
create_list(:order, 3, user: user, status: 'completed')
expect(User.active_customers.count).to eq(1)
end
end
end
Run your tests:
bundle exec rspec spec/models/user_spec.rb
Pushing Through CI/CD
git checkout -b fix/rails-scope-chain,git add app/models/user.rb,git commit -m "fix: add joins(:orders) to active_customers scope",git push origin fix/rails-scope-chain
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ['5432:5432']
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.3'
bundler-cache: true
- run: bin/rails db:setup
- run: bundle exec rspec
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
gem install bugstack
Step 2: Initialize
require 'bugstack'
Bugstack.init(api_key: ENV['BUGSTACK_API_KEY'])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Add the necessary joins to the scope.
- Add model specs covering the scope.
- Check that other scopes chained with this one still work.
- Open a pull request.
- Merge and verify in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other components are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
joins performs an INNER JOIN and is needed for WHERE conditions on the joined table. includes does eager loading for performance. Use joins in scopes that filter on associated columns.
Yes, but ensure each scope is self-contained with its own joins. Use merge to combine scopes from different models safely.