我添加了一個我認爲本身須要的表,但如今再也不計劃使用它。 我應該如何刪除那張桌子? 數據庫
我已經運行了遷移,所以該表位於數據庫中。 我認爲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)