Last Updated: February 25, 2016
·
1.069K
· MeetDom

Rails/Rake Database Rebuild Timesaver

Rails provides some great productivity timesavers, but one thing I see again and again when people are first building a project or prototyping, is what I call the rake db merry-go-round:

$ rake db:drop
$ rake db:create
$ rake db:migrate
$ rake db:seed

Time and time again we find ourselves retyping these commands, or cycling through our command list in the console to save us typing them again.

A few years ago I wrote some quick and dirty rake tasks to augment the Rails ones. This is one that I include in every new project:

# \lib\tasks\db_rebuild.rake
namespace :db do
  desc "Drop, create, migrate and seed the database  for the current RAILS_ENV"
  task :rebuild => :environment do
    puts "---> Dropping database... \n\n"
    Rake::Task["db:drop"].invoke
    puts "---> Dropped! \n\n---> Creating database... \n\n"
    Rake::Task["db:create"].invoke
    puts "---> Created! \n\n---> Running migrations... \n\n"
    Rake::Task["db:migrate"].invoke
    puts "---> Migrated! \n\n---> Seeding tables... \n\n"
    Rake::Task["db:seed"].invoke
    puts "---> Seeded! \n\nFinished rebuilding."
  end
end

To invoke this task, you can simply issue the following in the console:

$ rake db:rebuild

All output from the individual tasks are still sent to stdout.

This task will also be listed when you invoke:

$ rake -T

Rake is an incredibly versatile tool and there's a lot you do with it, this quick tip doesn't even touch the surface.

I hope this helps someone out there who feels stuck on the merry-go-round.