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

rake db:recreate

这可能吗?


当前回答

你可以简单地跑

rake db:设置

如果你用一些数据创建了种子文件,它会删除数据库,创建新的数据库并从种子中填充db。

其他回答

TL;DR——我在开发过程中使用这个rake脚本删除所有内容,包括模式文件,然后直接从迁移脚本重新构建。它同时重建开发和测试数据库。这是我发现的唯一能保证一切都如我所愿的方法。我用了很多年都没有问题。

# lib/tasks/db_rebuild.rake

require 'fileutils'

namespace :db do
  desc "Create DB if it doesn't exist, then migrate and seed"
  task :build do
    Rake::Task["db:create"].invoke
    Rake::Task["db:migrate"].invoke
    Rake::Task["db:seed"].invoke
  end

  desc "Drop database and rebuild directly from migrations (ignores schema.rb)"
  task :rebuild do
    raise "Task not permitted in production." if ENV["RAILS_ENV"] == "production"

    puts "*** Deleting schema.rb"
    system "rm -f #{Rails.root.join("db", "schema.rb")}"

    puts "*** Deleting seed lock files"
    system "rm -f #{Rails.root.join("db", ".loaded*")}"

    puts "*** Recreate #{ENV['RAILS_ENV']} database"
    begin
      Rake::Task['environment'].invoke
      ActiveRecord::Base.connection
    rescue ActiveRecord::NoDatabaseError
      # database doesn't exist yet, just create it.
      Rake::Task["db:build"].invoke
    rescue Exception => e
      raise e
    else
      Rake::Task["db:environment:set"].invoke
      # https://github.com/rails/rails/issues/26319#issuecomment-244015760
      # ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] = '1'
      Rake::Task["db:drop"].invoke
      Rake::Task["db:build"].invoke
    end
    Rake::Task["db:retest"].invoke
  end

  desc "Recreate the test DB"
  task :retest do
    system("rake db:drop db:build RAILS_ENV=test")
  end
end

基本原理——所有提供的解决方案的问题是Rails提供的本地Rake任务依赖于schema.rb。当我做大量的数据建模时,我直接对迁移文件进行更改;只有在它们被提交到上游之后,我们才将它们视为不可变的。但是如果我对迁移文件做了更改,它们就不会反映在schema.rb中。

另一个问题是开发环境和测试环境之间的区别。Rails db任务独立地处理它们,但根据我的经验,开发和测试数据库应该始终保持对等,这意味着在开发时我必须运行大量重复的数据库清理。

我在Terminal中使用了以下一行。

$ rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare

我将其作为shell别名,并将其命名为remigrate

到现在为止,你可以很容易地“链接”Rails任务:

$ 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+

在Rails 4中,所需要的是

$ rake db:schema:load

这将删除您的DB上的全部内容,并根据您的模式重新创建模式。Rb文件,而不必逐一应用所有迁移。

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

如果你用一些数据创建了种子文件,它会删除数据库,创建新的数据库并从种子中填充db。