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

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

我试过了:

rails generate migration drop_tablename

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

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


当前回答

替代引发异常或试图重新创建一个现在空的表-同时仍然启用迁移回滚,重做等-

def change
  drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end

其他回答

您并不总是能够简单地生成迁移来拥有您想要的代码。您可以创建一个空迁移,然后用您需要的代码填充它。

你可以在这里找到关于如何在迁移中完成不同任务的信息:

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

更具体地说,你可以看到如何使用以下方法删除一个表:

drop_table :table_name

我认为,为了完全“正式”,你需要创建一个新的迁移,并把drop_table放在self.up中。自我。方法应该包含完整地重新创建表的所有代码。假定代码可以从模式中提取。Rb在你创建迁移的时候。

添加代码来创建一个您知道不再需要的表,这似乎有点奇怪,但这将保持所有迁移代码的完整和“正式”,对吗?

我只是对我需要放下的桌子做了这样的操作,但老实说,我没有测试“放下”,也不确定我为什么要这么做。

首先,生成一个具有任意名称的空迁移。这样做很重要,因为它创建了适当的日期。

rails generate migration DropProductsTable

这将在/db/migrate/目录下生成一个。rb文件,如20111015185025_drop_products_table.rb

现在编辑该文件,如下所示:

class DropProductsTable < ActiveRecord::Migration
  def up
    drop_table :products
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

我唯一添加的东西是drop_table:products和raise ActiveRecord::IrreversibleMigration。

然后运行rake db:migrate,它会帮你删除这个表。

帮助文档

在迁移中,您可以通过以下方式删除表:

drop_table(table_name, **options)

选项:

:力 设置为:cascade也可以删除依赖对象。默认为false

: if_exists 设置为true仅在表存在时删除它。默认为false

例子:

Create migration for drop table, for example we are want to drop User table rails g migration DropUsers Running via Spring preloader in process 13189 invoke active_record create db/migrate/20211110174028_drop_users.rb Edit migration file, in our case it is db/migrate/20211110174028_drop_users.rb class DropUsers < ActiveRecord::Migration[6.1] def change drop_table :users, if_exist: true end end Run migration for dropping User table rails db:migrate == 20211110174028 DropUsers: migrating =============================== -- drop_table(:users, {:if_exist=>true}) -> 0.4607s

你能做的最好的办法就是

rails g migration Drop_table_Users

然后执行以下操作

rake db:migrate