Rails migrations squash

Sooner or later, in a Ruby on Rails application, the db/migrations directory tends to pile up with obsolete, unused migrations.

The best way I found to squash them into one file and move on is to:

  • Backup all the db/migrations directory, somewhere outside the project or don’t forget to add it to .gitgnore If you decide to keep it inside of it
  • Create a new Rails migration e.g. rails g migration squash_v1
  • Copy the contents of db/schema.rb file inside the ActiveRecord::Schema.define(version: xxxxyyyyzzzz) do block
  • Open the db/migrations/xxxxxxxxxxxx_squash_v1.rb file and paste inside the block
    class SquashMigrationV1 < ActiveRecord::Migration[6.1]
    def change
    ....
    

– Done –