빠른 참조

Rails 데이터베이스 마이그레이션 치트시트

Rails 데이터베이스 마이그레이션 빠른 참조 가이드: create_table, 컬럼 타입, 외래 키, 복합 인덱스, 롤백 가능한 변경사항 및 Rake 태스크.

· 게시일

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

# 최근 마이그레이션 1단계 롤백
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

참고 자료

관련 주제