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

我已经运行了迁移,所以这个表在我的数据库中。我认为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"

其他回答

如果有人在寻找如何在SQL中做到这一点。

从终端输入rails dbconsole

输入密码

在控制台做

使用db_name;

DROP TABLE table_name;

exit

请不要忘记从模式中删除迁移文件和表结构

帮助文档

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

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

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

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

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

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

你能做的最好的办法就是

rails g migration Drop_table_Users

然后执行以下操作

rake db:migrate

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

rails c

Type

ActiveRecord::Migration.drop_table(:tablename)

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

rails db:migrate