How to Fix Migration Error in Rails: Simple Steps
rails db:migrate:status to identify pending or failed migrations and use rails db:rollback or fix the migration file before rerunning rails db:migrate.Why This Happens
Migration errors in Rails usually happen because of syntax mistakes, missing columns, or conflicts with existing database schema. For example, trying to add a column that already exists or using wrong data types can cause the migration to fail.
class AddAgeToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :age, :string add_column :users, :age, :integer end end
The Fix
To fix this error, remove the duplicate column addition and ensure each column is added only once with the correct data type. Also, check the migration history to avoid conflicts.
class AddAgeToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :age, :integer end end
Prevention
To avoid migration errors, always check your migration files for duplicates or syntax errors before running them. Use rails db:migrate:status to track migration states and rails db:rollback to undo faulty migrations. Writing small, incremental migrations and testing them locally helps prevent conflicts.
Related Errors
Other common migration errors include:
- Missing table: Happens if you reference a table that does not exist yet.
- Wrong data type: Using unsupported or misspelled data types causes failure.
- Pending migrations: Trying to run migrations when previous ones failed.
Fix these by verifying schema, correcting types, and running migrations in order.