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

rake db:recreate

这可能吗?


当前回答

在Rails 6中,有一种方便的方法来重置DB并再次播种:

rails db:seed:replant # Truncates tables of each database for current environment and loads the seeds

https://weblog.rubyonrails.org/2019/3/15/this-week-in-rails-security-fixes-bulk-insert-and-upsert-seeds-replanting/

其他回答

你可以使用 Db:reset -用于运行Db:drop和Db:setup或 Db:migrate:reset -运行Db:drop, Db:create和Db:migrate。

依赖于你想要使用现有的模式

3个选项,结果相同:

1. 所有的步骤:

  $ rake db:drop           # deletes the database for the current env
  $ rake db:create         # creates the database for the current env
  $ rake db:schema:load    # loads the schema already generated from schema.rb / erases data
  $ rake db:seed           # seed with initial data

2. 重置:

  $ rake db:reset          # drop / schema:load / seed

3.迁移:重置:

  $ rake db:migrate:reset  # drop / create / migrate
  $ rake db:seed

注:

如果使用schema:load比执行所有迁移都快,但结果相同。 所有数据都将丢失。 您可以在一行中运行多个耙。 使用rails 3。

从命令行运行

rake db:migrate:reset

更新:在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

只需发布以下步骤:删除数据库,然后重新创建它,迁移数据,如果有种子,则播种数据库:

rake db:drop db:create db:migrate db:seed

由于rake的默认环境是开发环境,如果您在spec测试中看到异常,您应该为测试环境重新创建db,如下所示:

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

在大多数情况下,测试数据库在测试过程中被播种,因此db:seed任务操作不需要通过。否则,你必须准备数据库:

rake db:test:prepare

or

RAILS_ENV=test rake db:seed

此外,要使用重建任务,您可以添加到Rakefile以下代码:

namespace :db do
   task :recreate => [ :drop, :create, :migrate ] do
      if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
         Rake::Task[ 'db:seed' ].invoke
      end
   end
end

然后问题:

rake db:recreate