๐Ÿ“ฆ

Migrations

Version control database schema with code

Migration is a system for managing database schema changes in Ruby code. Instead of running SQL directly, you write migration files and apply them with rails db:migrate.

# db/migrate/20240101000000_create_posts.rb
class CreatePosts < ActiveRecord::Migration[8.0]
  def change
    create_table :posts do |t|
      t.string :title, null: false
      t.text :content
      t.references :user, null: false, foreign_key: true
      t.string :status, default: 'draft'
      t.timestamps  # auto-adds created_at, updated_at
    end

    add_index :posts, :status
  end
end

Key commands:

  • rails db:migrate โ€” run pending migrations

  • rails db:rollback โ€” undo last migration

  • rails db:migrate:status โ€” check migration status

The timestamp in the filename (20240101000000) determines execution order, and applied migrations are recorded in the schema_migrations table.

Key Points

1

rails generate migration CreatePosts title:string content:text โ†’ migration file generated

2

Define schema changes in the change method of generated file

3

Use DSL: create_table, add_column, remove_column, rename_column, etc.

4

Run rails db:migrate โ†’ converted to SQL and applied to DB

5

db/schema.rb auto-updates (current schema snapshot)

6

Rollback with rails db:rollback (change method auto-reverses)

Pros

  • Version control DB schema with Git
  • Automated schema sync between team members
  • Auto-rollback support via change method
  • DB-agnostic DSL

Cons

  • Production migrations need caution (data loss risk)
  • Large table migrations take long time
  • No rollback without down method
  • Migration files keep accumulating

Use Cases

Table creation/deletion Column addition/modification/deletion Index addition Foreign key setup Schema sync across teams