What is Migration in Rails: Explanation and Example
migration is a way to change your database schema over time in a structured and version-controlled manner. It lets you create, modify, or delete tables and columns using Ruby code instead of writing raw SQL.How It Works
Think of a migration as a recipe for your database. Just like a recipe tells you how to prepare a dish step-by-step, a migration tells Rails how to change the database structure step-by-step. Each migration file describes one change, like adding a new table or changing a column.
Rails keeps track of which migrations have been applied, so it knows the current state of your database. When you run migrations, Rails applies only the new changes in order. This helps teams work together without messing up the database.
It’s like having a history book for your database changes, so you can move forward or backward safely and keep your data organized.
Example
This example shows a migration that creates a users table with name and email columns.
class CreateUsers < ActiveRecord::Migration[7.0] def change create_table :users do |t| t.string :name t.string :email t.timestamps end end end
When to Use
Use migrations whenever you need to change your database structure in a Rails app. This includes creating new tables, adding or removing columns, or changing column types.
For example, when you add a new feature that requires storing extra information, you create a migration to update the database. Migrations help keep your database in sync with your app code and make it easy to share changes with your team.
Key Points
- Migrations are Ruby classes that describe database changes.
- They keep your database schema versioned and organized.
- Run migrations with
rails db:migrateto apply changes. - They help teams collaborate without conflicts.
- You can rollback migrations to undo changes if needed.