The Hitchhiker’s Guide to Ruby On Rails Galaxy

Records of my voyage through RoR Galaxy

Excellent rake task code snippet to completely rebuild & migrate your db

Posted by arjunghosh on January 4, 2008

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
end

desc ‘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.

2 Responses to “Excellent rake task code snippet to completely rebuild & migrate your db”

  1. […] To seed the database with initial database:- Run the following command: rake db:populate This will populated the database with initial data as written in populate rake file. Also a rake task called rebuild has been created so that it becomes easy to do the above steps from dropping a db, re-creating the db,running all the migration and then finally populating it with the initial seed data. Run the following command:rake db:rebuild. [NOTE:This rebuild rake task will easily do all the above db related steps. See my previous post for “How to create a rake db:rebuild task” […]

  2. Alexwebmaster said

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: