With Rails Migration, you can easily add or update your DB schema with a command “rake db:migrate“.
But if you just realize that you gave the wrong datatype for your new column or you want to rename your new column, you may want to rollback to your previous schema version and re-run the update again. To rollback to your previous schema, you need issue the command:
# rake db:migrate VERSION=prev_version
where prev_version is the last version number of your DB schema, you need to find it out either by checking your last db migration files name or check the SCHEMA table in your DB. This apparently is not very convinient.
To be a little smarter, try putting the following code into a file called <RAILS_HOME>/lib/tasks/rollback.task, this will let you achieve the above by just issuing a single command like:
# rake db:rollback
additionally, to check the current DB schema version:
# rake db:current
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
namespace :db do
desc 'get current schema version'
task :current => :environment do
puts ActiveRecord::Migrator.current_version
end
end
