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

rake db:recreate

这可能吗?


当前回答

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。

其他回答

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

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

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

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

您可以使用以下命令行:

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

今天我对rails模式做了一些更改。我意识到我需要在一个层次结构中增加两个模型,并删除其他一些模型。需要对模型和控制器进行许多小的更改。

我添加了两个新模型并创建了它们,使用:

rake db:migrate

然后我编辑模式。rb文件。我手动删除了不再需要的旧模型,根据需要更改外键字段,只是重新排序了一下,让它对我来说更清楚。我删除了所有的迁移,然后通过以下方式重新运行构建:

rake db:reset

它工作得很完美。当然,所有的数据都必须重新加载。Rails意识到迁移已经被删除,并重置了高水位标记:

-- assume_migrated_upto_version(20121026094813, ["/Users/sean/rails/f4/db/migrate"])

要删除一个特定的数据库,你可以在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