How to rollback Rails database migrations

When you perform database migrations in Rails you use the following command:

rake db:migrate
If you want to roll back your change to need need to find out what version your database is currently at and then roll back to a previous version:
rake db:migrate VERSION=<version to roll back to>
I've never liked this way to roll back, seems to much like hard work to me so I found a migration rollback script on the programmingishard site and simplified so that it only rollback by one version:
    namespace :db do
namespace :migrate do
desc "Rollback the database schema to the previous version"
task :rollback => :environment do
previous_version = ActiveRecord::Migrator.current_version.to_i - 1
ActiveRecord::Migrator.migrate("db/migrate/", previous_version)
puts "Schema rolled back to previous verison (#{previous_version})."
end
end
To use this scriptlet, copy and paste the code into a file called db_rollback.rake and place it the lib/tasks directory within your Rails application.

To use it to roll back your most recent migration simply run:
rake db:migrate:rollback
Technorati Tags: , , , , , , ,

4 Comments:

Ravin Dave D said...

Behold, for I am become a cow, the mo-oer of worlds.

Anonymous said...

I tried a :
"rake db:migrate VERSION=X" to see what it did ..."

It removed all my my database tables

DON'T DO IT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

Paul Clarke said...

Useful info. I managed to rollback using "rake db:migrate VERSION=002" where the current version was named "003_add_test_data.rb" and the previous version named "002_add_price.rb". Thanks for the help.

abeacock said...

Paul, you can also just use "2" as your version number as Rails equates "002" as "2" internally anyway.

Glad you found my post some use though! :)