我有一个充满数据的Ruby on Rails开发数据库。我想删除所有东西,重建数据库。我正在考虑使用类似的东西:

rake db:recreate

这可能吗?


当前回答

因为在开发过程中,您总是希望重新创建数据库,所以可以在lib/tasks文件夹中定义一个rake任务。

  namespace :db do
      task :all => [:environment, :drop, :create, :migrate] do
   end 
end

在终端中运行

rake db:all

它将重新构建数据库

其他回答

我知道两种方法:

这将重置你的数据库并重新加载你当前的模式:

rake db:reset db:migrate

这将破坏你的数据库,然后创建它,然后迁移你当前的模式:

rake db:drop db:create db:migrate

在这两种情况下,所有数据都会丢失。

在rails 4.2上,删除所有数据,但保留数据库

$ bin/rake db:purge && bin/rake db:schema:load

https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md

我认为运行这个命令的最好方法是:

**rake db:reset** it does db:drop, db:setup
 rake db:setup does db:create, db:schema:load, db:seed

您可以使用以下命令行:

rake db:drop db:create db:migrate db:seed db:test:clone

更新:在Rails 5中,这个命令可以通过以下命令访问:

rails db:清除db:创建db:迁移RAILS_ENV=test


在最新的rails 4.2版本中,你现在可以运行:

rake db:purge 

来源:提交

# 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

它可以像上面提到的那样一起使用:

rake db:purge db:create db:migrate RAILS_ENV=test