Main Contents

Keeping Your Rails Migrations Clean

ruby, software development

I’m working my way through a for fun side project using Rails 1.1 and I’ve been using ActiveRecord migrations instead of the older style SQL scripts. I like them a lot because it allows me to continue to stay in Ruby. Still each time you want to make a change to a table you need to create a new migration script.

There’s a downside to migrations. Over time, your schema definition will be spread across a number of separate migration files, with many files potentially affecting the definition of each table in your schema. When this happens, it becomes difficult to see exactly what each table contains.

-Agile Development with Rails 2nd Edition (Beta)

After a bit of hunting I settled on my current fix. Keep all the changes one per table in their Create ActiveRecord Migration files. Keep all the data migrations in a separate file. When you alter one of them and need to reset your database run two commands:

rake db:migrate VERSION=0
rake db:migrate

Presto, your database is back to a clean state.

Ed Gibbs @ July 23, 2006

3 Comments

  1. assaf July 24, 2006 @ 7:42 am

    I just did a migration that splits a table in two, so I can have multiple values associated with the main entity.

    Once pushed into production, there’s no going back without losing new data.

    So I always treated migrations as patching the schema. Like SVN diff they tell you what change is made, they’re part of a bigger revision, but they don’t show the resulting code.

    The authoritize schema is still the snapshot. rake db:structure:dump.

  2. Ed Gibbs July 25, 2006 @ 8:36 pm

    Yes, once I get to production and have real data, I’ll have to change practice a bit. Dropping the whole thing is working for me right now in development/test mode.

Leave a comment


Feed