Collapsing old Rails Migrations

I don't do this, but here's how I would if pressed.

“Wildebeests on charred grass.” Photo by Susan Jane Golding. Used under a Creative Commons CC BY 2.0 License. https://flickr.com/photos/sjgolding/29694808950

Earlier today, Jason Garber asked,

#RubyOnRails folks: hit me with your hot takes on how to manage/archive/delete your app’s “old” migrations.

My quick response was, “Why bother?” and I generally stand by that. Sure the directory gets large, but it doesn’t hurt anything. New ones always go the the end anyway. In large apps, a new developer might not want to run all of them from the beginning and do a rails db:schema:load on setup. That’s fine. But you get extra nerd points if all migrations still work years later!

But what if you still wanted to clean them up? Here’s how I’d do it.

1. Add a new migration

$ rails generate migration collapse_old_migrations

Then, I’d copy everything from schema.rb into there. Easy. Mostly done.

2. Add some quick & dirty cleverness

Now, this migration will bomb if you try to run it, as you already have all these tables. Same on coworkers’ machines, and your production environment. In each environment, the migration number is tracked to know if it has run before.

So what I’d do is immediately comment out everything in this migration. Make it look empty.

Commit it and let it run everywhere.

3. Clean up

Now, come back some time later and uncomment everything in that migration. Anyone who’s already run it won’t re-run it, so we’re “safe” now. Finally, delete all the old migrations that you just obsoleted.

That’s it, done! A new coworker will pick up the project and only see this migration (and any newer) and not know what they’ve missed. An existing coworker won’t know anything happened.

Photo of Daniel Morrison

Daniel founded Collective Idea in 2005 to put a name to his growing and already full-time freelance work. He works hard writing code, teaching, and mentoring.

Comments