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

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

我试过了:

rails generate migration drop_tablename

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

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


当前回答

我需要删除我们的迁移脚本以及表本身……

class Util::Table < ActiveRecord::Migration

 def self.clobber(table_name)   
    # drop the table
    if ActiveRecord::Base.connection.table_exists? table_name
      puts "\n== " + table_name.upcase.cyan + " ! " 
           << Time.now.strftime("%H:%M:%S").yellow
      drop_table table_name 
    end

    # locate any existing migrations for a table and delete them
    base_folder = File.join(Rails.root.to_s, 'db', 'migrate')
    Dir[File.join(base_folder, '**', '*.rb')].each do |file|
      if file =~ /create_#{table_name}.rb/
        puts "== deleting migration: " + file.cyan + " ! "
             << Time.now.strftime("%H:%M:%S").yellow
        FileUtils.rm_rf(file)
        break
      end
    end
  end

  def self.clobber_all
    # delete every table in the db, along with every corresponding migration 
    ActiveRecord::Base.connection.tables.each {|t| clobber t}
  end

end

从终端窗口运行:

$ rails runner "Util::Table.clobber 'your_table_name'"

or

$ rails runner "Util::Table.clobber_all"

其他回答

打开rails控制台

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

你不能简单地运行drop_table:table_name,相反,你可以通过运行以下命令创建一个空迁移: rails迁移drop安装

然后你可以把这个添加到空迁移中:

class DropInstalls < ActiveRecord::Migration
  def change
    drop_table :installs
  end
end

然后在命令行中运行rails db:migrate,这将删除安装表 在这里找到了解决方案

警告:这样做的风险由您自己承担,正如@z-atef和@nzifnab正确指出的那样,Rails不会意识到这些更改,您的迁移序列填充失败,您的模式将与您的同事的不同。这仅仅是为当地的发展修修补补提供资源。


虽然这里提供的答案工作正常,但我想要一些更“直接”的东西,我在这里找到了:链接 首先进入rails控制台:

$rails console

然后输入:

ActiveRecord::Migration.drop_table(:table_name)

完成了,为我工作了!

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

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

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

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)