Rebase Rails migrations in a long running project

In general, you don’t need to clean up old migrations. If you’re running db:migrate from scratch (no existing db), Rails uses db/schema.rb to create the tables instead of running every migration. Otherwise, it only runs the migrations required to upgrade from the current schema to the latest.

If you still want to combine migrations up to a given point into a single one, you could try to:

  • migrate from scratch up to the targeted schema using rake db:migrate VERSION=xxx
  • dump the schema using rake db:schema:dump
  • remove the migrations from the beginning up to version xxx and create a single new migration using the contents of db/schema.rb (put create_table and add_index statements into the self.up method of the new migration).

Make sure to choose one of the old migration version numbers for your aggregated new migration; otherwise, Rails would try to apply that migration on your production server (which would wipe your existing data, since the create_table statements use :force⇒true).

Anyway, I wouldn’t recommend to do this since Rails usually handles migrations well itself. But if you still want to, make sure to double check everything and try locally first before you risk data loss on your production server.

Leave a Comment