The defest of leppards

If you have any moderately old rails applications in production, and you find
yourself screwing around with indexes in newer migrations, keep in mind that the
index naming convention rails uses changed at some point (specifically, in
changeset 4768).

So if you had this in an application from a while ago - specifically, if you
have an application that was in production prior to the 1.2 release of rails -
and you have a migration like this…

…assuming that you have entirely dropped and rebuilt your development
environment database at some point since you wrote the original migration (which
may be quite some time ago, at this point) - the migrations will run fine, and
your local development database will have the indexes you want it to.

However, when it’s time to go to production, and you’re dealing with a database
on the live cluster which has not been reset/rebuilt/whatever since it’s
initial deployment (because seriously…why would it have?), you will find that
migration #297 does not run against the production data because the application
will try to use a different name than what it originally used when it was
running an older version of rails with the former naming style. Hmmm.

This is not a problem though, rails gives us a :name option on indexes in
migrations. You can change your new migration to reference what you know the
old indexes were called…

Even though you can deploy now and the production database will run the
migrations successfully, what about the new developers coming onto the project
who are going to be building a database from scratch? Now we need to go modify
the old migration so that it produces an index named the way the indexes were
originally named back in the time that they were actually run on the production
server, using that earlier version of the application and of rails.

This is all sort of annoying, and violates the never commit a change to an old
migration rule. However, since the framework doesn’t handle it for you, you get
to handle it for yourself.

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.