3
Posted January 7, 2011 by Spyros in Ruby on Rails
 
 

Custom Rails Task to Drop, Create, Migrate and Seed a Database

reset
reset

If you have been using Ruby on Rails to create your websites or web applications, i’m pretty sure that you are looking for a fast and easy way to drop your database and recreate it, as well as feed it with your fixtures data. This procedure is actually 4 different tasks, but using a simple trick, you can make it very easy for you.

With rails, you can create your own custom task that will enable you to do that very quickly. The procedure is simple. In your Rails application folder, go to /lib/tasks and create a new rake file. I prefer to name it “reset_db.rake“. Open it and inside write the lines :

namespace :db do
  desc "Drop, create, migrate then seed the database"
  task :reset_db => :environment do
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:migrate'].invoke
    Rake::Task['db:fixtures:load'].invoke
  end
end

Now, whenever you want to recreate and totally reset your database, you just have to execute the command “rake db:reset_db”. This will automatically drop the database, recreate it, run the migrations and ultimately load the fixtures located at /test/fixtures. Hope that saves you as much time as it saves for me :)


Spyros