Rails: ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email"
A unique index rejected an insert/update because the value already exists.
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email"Mysql2::Error: Duplicate entry 'a@b.com' for key 'index_users_on_email'ActiveRecord::RecordNotUnique (PG::UniqueViolation)SQLite3::ConstraintException: UNIQUE constraint failed: users.emailKey (id)=(1) already exists Meaning
Validations (validates :email, uniqueness: true) don't prevent races; the DB constraint does. Rescue RecordNotUnique, use find_or_create_by inside a retry, or upsert. Also check sequences out of sync after data imports (PG::UniqueViolation ... Key (id)=(1)).
Common causes
- Duplicate email/slug/code
- Race between validation and insert
- Primary key sequence behind max(id) after import
- Seeds run twice
- Retry causing double insert
⚡ Quick fix
begin; ...; rescue ActiveRecord::RecordNotUnique; retry; endorupsert- Reset sequences:
ActiveRecord::Base.connection.reset_pk_sequence!("users") - Keep a unique index plus validation
Detailed fix by platform
Rails
User.upsert({ email: e, name: n }, unique_by: :email)
How to diagnose
- Index — Which?
- Race — Concurrent?
- Sequence — In sync?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in Ruby / Rails
- ActiveRecord::PendingMigrationError Rails: ActiveRecord::PendingMigrationError — Migrations are pending. To resolve this issue, run: bin/rails db:migrate
- undefined method for nil Ruby: NoMethodError: undefined method `x' for nil (nil:NilClass)
- ActionController::InvalidAuthenticityToken Rails: ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity)
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 5 Nov 2026