A custom Rake task to reset and seed your database

Published 29 April 08 by Justin French, 1 comments

No matter how obvious I think this stuff is now, there was a point when it wasn’t, so I’m trying to share more. Here’s something I do a lot during the initial development process of a Rails application:

  1. drop the current database
  2. re-create it
  3. run all the migrations
  4. load in some sample data from the fixtures (or elsewhere)

The good news is that Rails provides a Rake task for each of these (run $ rake --tasks | grep 'db' to see plenty more), so if you really like typing you can just run these four commands:

  1. rake db:drop
  2. rake db:create
  3. rake db:migrate
  4. rake db:fixtures:load

No way, typing is for suckers. What you (should) want to do is encapsulate this thing you want to do over and over as a new custom Rake task. Let’s go with rake db:seed.

Create a new file application.rake (or db.rake, whatever) in RAILS_ROOT/lib/tasks with the following:


namespace :db do
  desc "Drop, create, migrate then seed the database"
  task :seed => :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

Give it a try, I’ll wait. Warning: This will totally hose your database!

And we can clean this up too. task :seed => :environment is telling rake to run the ‘environment’ task (it loads the Rails environment) before running the rest of the task. We can actually pass in s set of tasks as an Array:


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

Finally, I’ll sleep better tonight if you make sure this task can only run in the development environment (ensuring you can’t accidentally hose your production data), so let’s add another task ‘development_environment_only’ and include it in the task list:


namespace :db do
  desc "Raise an error unless the RAILS_ENV is development"
  task :development_environment_only do
    raise "Hey, development only you monkey!" unless RAILS_ENV == 'development'
  end
  desc "Drop, create, migrate then seed the development database"
  task :seed => [
    'environment', 
    'db:development_environment_only', 
    'db:drop', 
    'db:create', 
    'db:migrate', 
    'db:fixtures:load'
    ]
  end
end

Options

Search