我添加了一个我认为我将需要的表格,但现在不再计划使用它。我该如何移除那张桌子?

我已经运行了迁移,所以这个表在我的数据库中。我认为rails生成迁移应该能够处理这个问题,但我还没有弄清楚如何处理。

我试过了:

rails generate migration drop_tablename

但这只是产生了一个空迁移。

在Rails中删除表的“官方”方式是什么?


当前回答

你能做的最好的办法就是

rails g migration Drop_table_Users

然后执行以下操作

rake db:migrate

其他回答

您需要使用以下命令创建一个新的迁移文件

rails generate migration drop_table_xyz

并在新生成的迁移文件(db/migration/xxxxxxx_drop_table_xyz)中编写drop_table代码

drop_table :tablename

或者如果你想在不迁移的情况下删除表,只需打开rails控制台by

$ rails c

并执行以下命令

ActiveRecord::Base.connection.execute("drop table table_name")

或者你可以使用更简单的命令

ActiveRecord::Migration.drop_table(:table_name)

打开rails控制台

ActiveRecord::Base.connection.execute("drop table table_name")

手动编写迁移。例如:运行rails g migration DropUsers。

至于迁移的代码,我将引用Maxwell Holder的帖子Rails migration Checklist

BAD—运行rake db:migrate and then rake db:rollback将失败

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users
  end
end

GOOD -揭示了迁移不应该可逆的意图

class DropUsers < ActiveRecord::Migration
  def up
    drop_table :users
  end

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

BETTER -实际上是可逆的

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users do |t|
      t.string :email, null: false
      t.timestamps null: false
    end
  end
end

删除表/迁移

运行: $ rails生成迁移DropTablename

$ rails生成迁移DropProducts

我不能让它与迁移脚本一起工作,所以我继续使用这个解决方案。使用终端进入rails控制台:

rails c

Type

ActiveRecord::Migration.drop_table(:tablename)

这对我来说很有效。这将删除前一个表。别忘了跑步

rails db:migrate