Fix Migration Errors

This guide helps you diagnose and fix common migration errors.

Common Error: Table Already Exists

Error:

relation "users" already exists

Cause: Running migration twice or table was created manually.

Solutions:

  1. Check migration status:

puts migrator.applied_migrations
  1. Mark migration as applied (if table exists and is correct):

migrator.mark_as_applied(migration_number)
  1. Drop and recreate (development only):

schema.users.drop! if schema.table?(:users)

Common Error: Table Does Not Exist

Error:

relation "users" does not exist

Cause: Trying to alter or reference a table that wasn't created.

Solutions:

  1. Run migrations in order:

  1. Check migration order - ensure create comes before alter

Common Error: Column Already Exists

Error:

Solutions:

  1. Check if column exists before adding:

  1. Remove the column first if replacing:

Common Error: Cannot Drop Column

Error:

Cause: Foreign key or index depends on the column.

Solutions:

  1. Drop dependencies first:

Common Error: Null Constraint Violation

Error:

Cause: Adding NOT NULL column to table with existing data.

Solutions:

  1. Add with default value:

  1. Add as nullable, update, then add constraint:

Common Error: Foreign Key Violation

Error:

Cause: Referenced record doesn't exist.

Solutions:

  1. Ensure parent records exist first

  2. Set foreign key to nullable:

  1. Use ON DELETE CASCADE or SET NULL:

Debugging Migrations

Reset Database (Development Only)

Stuck Migration

If a migration failed halfway:

  1. Check what was created:

  1. Manually fix state:

  1. Drop partially created objects:

  1. Re-run migration:

Last updated

Was this helpful?