Active Recordマイグレーションを使用すると、生のSQL DDL文を書かずに純粋なRuby DSLを用いてデータベーススキーマを安全かつ段階的に進化させることができます。
マイグレーションCLIジェネレータ
# 新規テーブルマイグレーションの生成
bin/rails g migration CreateArticles title:string body:text published:boolean
# カラム追加マイグレーションの生成
bin/rails g migration AddViewsToArticles views:integer
# 中間テーブル(結合テーブル)の生成
bin/rails g migration CreateJoinTableUsersProjects users projects
# 未実行マイグレーションの適用
bin/rails db:migrate
# 直近のマイグレーションをロールバック
bin/rails db:rollback STEP=1
テーブルの作成 (create_table)
class CreateUsers < ActiveRecord::Migration[7.1]
def change
create_table :users do |t|
t.string :name, null: false
t.string :email, index: { unique: true }
t.text :bio
t.integer :login_count, default: 0
t.decimal :balance, precision: 10, scale: 2
t.boolean :active, default: true, null: false
t.jsonb :preferences, default: {}
# 外部キー参照
t.references :organization, null: false, foreign_key: true
t.timestamps # タイムスタンプ: created_at & updated_at
end
end
end
カラムとテーブルの変更
class AlterArticles < ActiveRecord::Migration[7.1]
def change
add_column :articles, :status, :string, default: "draft"
remove_column :articles, :legacy_field, :string
change_column_null :articles, :title, false
change_column_default :articles, :views, from: nil, to: 0
rename_column :articles, :author, :writer
add_index :articles, [:status, :created_at]
end
end
可逆的な変更 (Reversible)
def change
reversible do |dir|
dir.up do
execute "CREATE EXTENSION IF NOT EXISTS citext;"
end
dir.down do
execute "DROP EXTENSION IF EXISTS citext;"
end
end
end