我添加了一个我认为本身须要的表,但如今再也不计划使用它。 我应该如何删除那张桌子? 数据库
我已经运行了迁移,所以该表位于数据库中。 我认为rails generate migration
应该可以解决这个问题,可是我尚未弄清楚如何解决。 spa
我试过了: code
rails generate migration drop_tablename
但这只是一个空的迁移。 get
在Rails中删除表的“官方”方法是什么? it
虽然此处提供的答案正常工做,但我想要更多“简单易懂”的东西,但我在这里找到了它: 连接首先进入rails console: io
$rails console
而后输入: console
ActiveRecord::Migration.drop_table(:table_name)
完成了,为我工做! table
打开Rails控制台class
ActiveRecord::Base.connection.execute("drop table table_name")
我须要删除迁移脚本以及表自己... file
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"
ActiveRecord::Base.connection.drop_table :table_name
您须要使用如下命令建立新的迁移文件
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)