Rails Model-Safe Migrations

Posted:

Ever hear people complain about how Rails migrations suck? Or, maybe you think so yourself?

Whatever the answer, recently, a couple fellow Rails colleagues informed me of a practice they follow to make Rails migrations sturdier.

They redefine (or mock), inside each migration, the models and the parts of those models being used in the migration so that the migration works independently of the application code. That way, if the application code is ever refactored (like if the name of the model being used in the migration is changed), the migration still works!

I thought this was a nice solution to make migrations stronger, but there was just one problem... It didn't use Git!

We can strengthen migrations with Git by creating a rake db:commit command to automatically assign commits to new migrations by tagging the commit with the migration's filename. Then, we can rewrite rake db:migrate to checkout the correct version of the codebase before running each migration.

The new rake db:migrate command would look something like this:

The rake db:commit command would do exactly what our new rake db:migrate command does and add something like this at the end:

Perhaps we could write a Gem that does this. It would strengthen migrations without having to redefine our models inside them.