Wednesday 18 May 2011

5 useful Rails Migrations commands

So we all know Rails migrations are extremely powerful, they allow you to write exactly how you want to structure your data, without getting down to the SQL. It's also really convenient to have a database schema checked into your revision control. It's ridiculously straight forward.. until you start moving data around your database (assuming your not some kind of terminator sent from the future with enough hindsight to never need to refactor your database).

As a general rule of thumb, we should not be moving data around in the migration structure. Here's why:

  • Its hard to write migrations and remember the order that you removed tables
  • Its really hard to read
  • If a migration breaks half way because of the data then we have run half a migration and it fails when we try it again.
  • If we have models we need to keep them and mark them deprecated until the data can be moved, we may remove a model and break our migrations

Therefore its essential to take a database dump of your data. With large data sets this does not seem practical to move around which is why we need to write and up and down data migration scripts. These can easily be placed in rake tasks.

Anyway here are 5 useful commands to get you out of trouble if your migrations go wrong:

rake db:migrate VERSION=20080901210000
rake db:rollback
rake db:rollback STEP=3
rake db:migrate:redo STEP=3
rake db:migrate:down VERSION=20080906120000

No comments:

Post a Comment