The other day I came across a code snippet which completely automates the re-building and migrating of database. It also run all my rake task for db which I can include in it. All this is done by single line of code. I thought I will share it here.
1. First you need to create a rake file in your /lib/tasks folder of your Rails application. Say it is called
db_populate.rake
2. In this file, add all your customized rake tasks for your db like adding initial seed data to db,etc.
3. Then add the following code just before the end of the rake task :
desc ‘rebuild the database from scratch’
task :rebuild=> :environment do
p “Beggining the rebuild”
Rake::Task["db:drop_and_create"].invoke
Rake::Task["db:migrate"].invoke
Rake::Task["db:populate"].invoke
enddesc ‘destroy your database’
task :drop_and_create=> :environment do
db_name = ActiveRecord::Base.connection.current_database
p “Dropping the database”
ActiveRecord::Base.connection.drop_database(db_name)
p “Creating the database”
ActiveRecord::Base.connection.create_database(db_name)
db_config = YAML.load_file(File.join(RAILS_ROOT, “config”, “database.yml”))
ActiveRecord::Base.establish_connection(db_config[RAILS_ENV])
end
Now whenever you need to re-create your db and run all your migrations and run all your tasks for db, you need not go and run multiple commands like db:migrate, then db:your_rake_tasks, etc.
You can simply run the following:
rake db:rebuild
cool right.

