Rails DB迁移-如何删除表?

心已入冬 提交于 2020-02-27 09:31:11

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

我已经运行了迁移,因此该表位于数据库中。 我认为rails generate migration应该能够解决这个问题,但是我还没有弄清楚如何解决。

我试过了:

rails generate migration drop_tablename

但这只是一个空的迁移。

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


#1楼

虽然此处提供的答案正常工作,但我想要更多“简单易懂”的东西,但我在这里找到了它: 链接首先进入rails console:

$rails console

然后输入:

ActiveRecord::Migration.drop_table(:table_name)

完成了,为我工作!


#2楼

打开Rails控制台

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

#3楼

我需要删除迁移脚本以及表本身...

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'"

要么

$ rails runner "Util::Table.clobber_all"

#4楼

ActiveRecord::Base.connection.drop_table :table_name


#5楼

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

rails generate migration drop_table_xyz

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

drop_table :tablename

或者,如果您想删除表而不进行迁移,只需按以下方式打开Rails控制台:

$ rails c

并执行以下命令

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

或者您可以使用更简化的命令

ActiveRecord::Migration.drop_table(:table_name)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!