Whenever I create a new migration I want to make sure my down method works as well as my up. So, I always end up doing rake db:migrate, check the current version number, n, and then roll it back one using rake db:migrate VERSION=n-1. Sometimes I’m migrating up more than one version, so I want to roll back a few steps (rake db:migrate VERSION=n-3). This, of course, is cumbersome. So, I wrote a simple task to make it easier:
namespace :db do
desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
task :rollback => :environment do
step = ENV['STEP'] ? ENV['STEP'].to_i : 1
version = ActiveRecord::Migrator.current_version - step
ActiveRecord::Migrator.migrate('db/migrate/', version)
end
end
This lets me migrate up, and roll back to the previous version easily.
$ rake db:migrate $ rake db:rollback
And I can go back a certain number of steps just as easily.
$ rake db:rollback STEP=3
Hopefully somebody will find this as useful as I do.


Awesome! I can’t believe I never thought of this before… I’m adding this to my Rake arsenal right now.