0
0
RailsConceptBeginner · 3 min read

What is Migration in Rails: Explanation and Example

In Rails, a 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.

ruby
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end
Output
== 20240601000000 CreateUsers: migrating ====================================== -- create_table(:users) -> 0.0012s == 20240601000000 CreateUsers: migrated (0.0013s) =============================
🎯

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:migrate to apply changes.
  • They help teams collaborate without conflicts.
  • You can rollback migrations to undo changes if needed.

Key Takeaways

Migrations let you change your database schema using Ruby code instead of SQL.
They keep track of changes so your database stays organized and versioned.
Run migrations with rails commands to apply or rollback changes safely.
Use migrations whenever your app needs new or changed database tables or columns.
Migrations help teams work together by sharing database changes clearly.