Purge or recreate a Ruby on Rails database
I have a dev Ruby on Rails database full of data. I want to delete everything and rebuild the database. I'm thinking of using something like:
rake db:recreate
Is this possible?
Solution 1:
I know two ways to do this:
This will reset your database and reload your current schema with all:
rake db:reset db:migrate
This will destroy your db and then create it and then migrate your current schema:
rake db:drop db:create db:migrate
All data will be lost in both scenarios.
Solution 2:
On Rails 4, all needed is
$ rake db:schema:load
That would delete the entire contents on your DB and recreate the schema from your schema.rb file, without having to apply all migrations one by one.
Solution 3:
I use the following one liner in Terminal.
$ rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare
I put this as a shell alias and named it remigrate
By now, you can easily "chain" Rails tasks:
$ rake db:drop db:create db:migrate db:schema:dump db:test:prepare # db:test:prepare no longer available since Rails 4.1.0.rc1+
Solution 4:
Update: In Rails 5, this command will be accessible through this command:
rails db:purge db:create db:migrate RAILS_ENV=test
As of the newest rails 4.2 release you can now run:
rake db:purge
Source: commit
# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
task :purge => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.purge_current
end
It can be used together like mentioned above:
rake db:purge db:create db:migrate RAILS_ENV=test