Rolling back database migration one step in Rails

Ruby posted about 1 year ago by marko

I found this awesome trick to rollback a Rails database migration one step. Add the following code to Rakefile.

   1  namespace :db do
   2    desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
   3    task :rollback => :environment do
   4      step = ENV['STEP'] ? ENV['STEP'].to_i : 1
   5      version = ActiveRecord::Migrator.current_version - step
   6      ActiveRecord::Migrator.migrate('db/migrate/', version)
   7    end
   8  end

And roll back with a breeze.

   1  rake db:migrate
   2  rake db:rollback

Tagged rails, active record migration