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

rake db:recreate

这可能吗?


当前回答

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

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

在终端中运行

rake db:all

它将重新构建数据库

其他回答

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

要删除一个特定的数据库,你可以在rails控制台中这样做:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

然后再次迁移DB

$bundle exec rake db:migrate 

根据你想要的,你可以使用…

rake db:创建

从config/database中从头构建数据库。yml,还是……

rake db:模式:负载

根据您的模式从头构建数据库。rb文件。

在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/