我添加了一个我认为我将需要的表格,但现在不再计划使用它。我该如何移除那张桌子?
我已经运行了迁移,所以这个表在我的数据库中。我认为rails生成迁移应该能够处理这个问题,但我还没有弄清楚如何处理。
我试过了:
rails generate migration drop_tablename
但这只是产生了一个空迁移。
在Rails中删除表的“官方”方式是什么?
我添加了一个我认为我将需要的表格,但现在不再计划使用它。我该如何移除那张桌子?
我已经运行了迁移,所以这个表在我的数据库中。我认为rails生成迁移应该能够处理这个问题,但我还没有弄清楚如何处理。
我试过了:
rails generate migration drop_tablename
但这只是产生了一个空迁移。
在Rails中删除表的“官方”方式是什么?
当前回答
简单而正式的方式是这样的:
rails g migration drop_tablename
现在转到您的db/migrate,并寻找包含drop_tablename作为文件名的文件,并将其编辑为此。
def change
drop_table :table_name
end
那你就得跑
rake db:migrate
在你的控制台。
其他回答
我需要删除我们的迁移脚本以及表本身……
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"
ActiveRecord:: Base.connection。drop_table: table_name
你可以按照指南中的方式回滚一次迁移:
http://guides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations
生成迁移:
rails generate migration revert_create_tablename
编写迁移:
require_relative '20121212123456_create_tablename'
class RevertCreateTablename < ActiveRecord::Migration[5.0]
def change
revert CreateTablename
end
end
通过这种方式,您还可以回滚并用于恢复任何迁移
简单而正式的方式是这样的:
rails g migration drop_tablename
现在转到您的db/migrate,并寻找包含drop_tablename作为文件名的文件,并将其编辑为此。
def change
drop_table :table_name
end
那你就得跑
rake db:migrate
在你的控制台。
如果您想删除一个特定的表,您可以这样做
$ rails db:migrate:up VERSION=[Here you can insert timestamp of table]
否则,如果您想删除所有数据库,您可以这样做
$rails db:drop