Wednesday, January 31, 2007

Rails migrations and model changes

On our current project we use Rails migrations for table creation, table modification, and data initialization. Our migrations worked well enough when they were run incrementally through the course of normal development, but failed (seemingly intermittently) when running rake migrate against an empty database. However, running rake migrate again (picking up from where the failure occurred) seemed to magically solve the problem.

Magic in software is not a good thing. It indicates either ignorance in the programmer or bugs in the software. Fortunately this was just a case of ignorance. Our problems were:
  1. Failure to use ActiveRecord's reset_column_information after a migration modifies a table (or before a model is used in a migration).
  2. Failure to periodically test migrations from scratch.
Have you tested your migrations on an empty database? Do it now, rather than when you're trying to deploy your system for the first time.

For details, see the migration documentation here.


Scott said...

This is good information to know. I feel like the documentation on migrations that I've seen is sketchy at best, so it's good to see some more of it actually explained. Nice post.

I was just testing migrations out. After running a migration and creating my database items, I somehow expected my model class to automatically get created. Not so. So I ran a model generator, which then looked at my database and seemed to try creating YET ANOTHER migration despite the fact that it wasn't needed. This seems really wrong, but I can't find much of anything that gives any context about what you do to create your models along with using migrations.

Davina said...

Here is a really useful Rails Migrations cheatsheet in printable PDF format: Rails Migrations Cheatsheet Reference

Elmoe01 said...

Migrations are great but sometimes you get unexpected results.

But I still prefer to use migrations because I lessens the burden for me to think of the technicalities when tables in pure sql commands. What's also great is that you can sort of "undo" the changes like migrating to previous versions.

Jim said...

I understand your pain. Migrations can be flaky, but they're a necessary evil.

Atleast they're getting less intrusive. I just wrote up a blog post that outlines the command-line options available in Rails 2.0 for generating a migration to quickly add/remove columns for a given table.