Database Migration
Database migration in Ruby on Rails is a feature that allows developers to modify and manage the database schema over time in a consistent and version-controlled way.
Table of Contents
What is Database Migration in Ruby on Rails?
Database migration is a Rails mechanism for changing your database schema safely and predictably. Instead of manually altering tables or columns, migrations let you define changes in Ruby code, which Rails then applies to the database.
Migrations track the evolution of the database, making it easy to add, remove, or modify tables and columns while keeping your database in sync across development, staging, and production environments.
Why is Database Migration Useful?
Manual changes to the database can cause inconsistencies, especially in team environments. Migrations solve this by:
-
Providing version control for database changes
-
Ensuring consistent schema across all environments
-
Allowing rollback in case of errors
-
Simplifying collaboration in teams working on the same database
-
Making it easier to deploy updates without data loss
Migrations make managing database changes safer and more organized, reducing errors and confusion.
How Database Migration Works
Migrations are Ruby classes stored in db/migrate/ that define schema changes using methods like create_table, add_column, or remove_index.
Example: Creating a users table

Commands to manage migrations:
-
rails db:migrate → Applies new migrations to the database
-
rails db:rollback → Reverts the last migration
-
rails db:migrate:status → Shows which migrations have been applied
Rails keeps track of applied migrations in a special table called schema_migrations.
Where to Use Database Migration
-
Creating new tables and database structures
-
Modifying existing tables (adding/removing columns)
-
Adding indexes or constraints for performance and integrity
-
Tracking schema changes in team projects
-
Rolling back changes safely during development or deployment
In Summary
Database migration in Ruby on Rails provides a structured, version-controlled way to manage schema changes. By defining database updates in code, migrations ensure consistent, safe, and reversible changes, making Rails applications easier to develop, maintain, and deploy.