我有一个充满数据的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 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

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

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

rake db:migrate

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

rake db:reset

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

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

我知道两种方法:

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

rake db:reset db:migrate

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

rake db:drop db:create db:migrate

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

使用像

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

都在一行里。这更快,因为环境不会一次又一次地重新加载。

drop -删除数据库。

数据库:create -将创建数据库(主机/ Db /密码将从config/database.yml中获取)

Db:migrate -将从目录(Db /migration/.rb)*运行现有的迁移。

Db:seed -将在目录(Db /migration/seed.rb)中运行种子数据。

我通常喜欢:

rake db:reset

一下子做所有的事。

干杯!

在Rails 4中,所需要的是

$ rake db:schema:load

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