# Rails: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "users" does not exist

**Code:** `PG::UndefinedTable: relation does not exist` · **Category:** Ruby / Rails · **Seen on:** Ruby, PostgreSQL

Rails queried a table that isn't in the connected PostgreSQL database.

## Meaning

Migrations weren't run for that environment (`bin/rails db:migrate`), you're connected to the wrong database, or the schema search path excludes the schema. Check `RAILS_ENV`, `DATABASE_URL`, and `rails db:migrate:status`. In tests run `db:test:prepare`.

## Common causes

- Migrations not run in this environment
- Wrong DATABASE_URL/RAILS_ENV
- Test DB not prepared
- Table renamed/dropped
- Multi-schema `search_path` mismatch

## Quick fix

1. `bin/rails db:migrate` (or `db:schema:load`) for the right env
2. Check `bin/rails runner 'puts ActiveRecord::Base.connection.current_database'`
3. `bin/rails db:test:prepare` for tests

## Detailed fix by platform

### Rails

1. `bin/rails db:migrate:status | head && bin/rails runner 'p ActiveRecord::Base.connection.tables'`

## How to diagnose

1. **Env** — RAILS_ENV?
2. **DB** — Connected database?
3. **Migrations** — Applied?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/ruby/activerecord-statementinvalid-pg-undefinedtable)
