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:recrea
You can use
db:reset
- for run db:drop and db:setup or
db:migrate:reset
- which runs db:drop, db:create and db:migrate.
dependent at you want to use exist schema.rb
Depending on what you're wanting, you can use…
rake db:create
…to build the database from scratch from config/database.yml
, or…
rake db:schema:load
…to build the database from scratch from your schema.rb
file.
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+
Just issue the sequence of the steps: drop the database, then re-create it again, migrate data, and if you have seeds, sow the database:
rake db:drop db:create db:migrate db:seed
Since the default environment for rake
is development, in case if you see the exception in spec tests, you should re-create db for the test environment as follows:
RAILS_ENV=test rake db:drop db:create db:migrate
In most cases the test database is being sowed during the test procedures, so db:seed
task action isn't required to be passed. Otherwise, you shall to prepare the database:
rake db:test:prepare
or
RAILS_ENV=test rake db:seed
Additionally, to use the recreate task you can add into Rakefile the following code:
namespace :db do
task :recreate => [ :drop, :create, :migrate ] do
if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
Rake::Task[ 'db:seed' ].invoke
end
end
end
Then issue:
rake db:recreate
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
From the command line run
rake db:migrate:reset