kawabatas技術ブログ

試してみたことを書いていきます

Rails のマイグレーションファイルをまとめる

概要

jalkoby/squasher を使って、マイグレーションファイルをまとめたのでメモ。

db/structure.sqlスキーマ情報を管理している。

インストール

gem 'squasher'

bin/squasher を作成

$ bundle binstub squasher

使う

application.rb の下記をコメントアウトする

  # config.active_record.schema_format = :sql

実行する。※issue が対応されるまでは Bundler version 1.16.2 を使う。

$ bin/squasher 2018/09/13 -m 5.1

略

Squasher's created the `squasher` database for its needs.
It might be useful to keep it if any of your deleted migrations inserts data or
you squash migrations in a few steps (look at -r option).
Keep it (yes / no)?
no
Dropped database 'squasher'
Do you want to clean your database from the old schema migration records(yes/no)?
no

-s オプションを使うと、新たにできた xxxxx_init_schema.rb が SQL 形式になるので避けた。

class InitSchema < ActiveRecord::Migration[5.1]
  def up
    execute %q{

    略 SQL文

    }
  end
  def down
    raise ActiveRecord::IrreversibleMigration, "The initial migration is not revertable"
  end
end

application.rb のコメントアウトを戻す

  config.active_record.schema_format = :sql

db/schema.rb ができているので、削除する

db:drop db:create db:migrate を行い、structure.sql の差分を確認する