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 migrationsrails db:rollbackโ undo last migrationrails 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
rails generate migration CreatePosts title:string content:text โ migration file generated
Define schema changes in the change method of generated file
Use DSL: create_table, add_column, remove_column, rename_column, etc.
Run rails db:migrate โ converted to SQL and applied to DB
db/schema.rb auto-updates (current schema snapshot)
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