我添加了一个我认为我将需要的表格,但现在不再计划使用它。我该如何移除那张桌子?
我已经运行了迁移,所以这个表在我的数据库中。我认为rails生成迁移应该能够处理这个问题,但我还没有弄清楚如何处理。
我试过了:
rails generate migration drop_tablename
但这只是产生了一个空迁移。
在Rails中删除表的“官方”方式是什么?
我添加了一个我认为我将需要的表格,但现在不再计划使用它。我该如何移除那张桌子?
我已经运行了迁移,所以这个表在我的数据库中。我认为rails生成迁移应该能够处理这个问题,但我还没有弄清楚如何处理。
我试过了:
rails generate migration drop_tablename
但这只是产生了一个空迁移。
在Rails中删除表的“官方”方式是什么?
当前回答
手动编写迁移。例如:运行rails g migration DropUsers。
至于迁移的代码,我将引用Maxwell Holder的帖子Rails migration Checklist
BAD—运行rake db:migrate and then rake db:rollback将失败
class DropUsers < ActiveRecord::Migration
def change
drop_table :users
end
end
GOOD -揭示了迁移不应该可逆的意图
class DropUsers < ActiveRecord::Migration
def up
drop_table :users
end
def down
fail ActiveRecord::IrreversibleMigration
end
end
BETTER -实际上是可逆的
class DropUsers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :email, null: false
t.timestamps null: false
end
end
end
其他回答
首先,生成一个具有任意名称的空迁移。这样做很重要,因为它创建了适当的日期。
rails generate migration DropProductsTable
这将在/db/migrate/目录下生成一个。rb文件,如20111015185025_drop_products_table.rb
现在编辑该文件,如下所示:
class DropProductsTable < ActiveRecord::Migration
def up
drop_table :products
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
我唯一添加的东西是drop_table:products和raise ActiveRecord::IrreversibleMigration。
然后运行rake db:migrate,它会帮你删除这个表。
Run
rake db:migrate:down VERSION=<version>
其中<version>是您想要恢复的迁移文件的版本号。
例子:-
rake db:migrate:down VERSION=3846656238
您可以简单地从rails控制台删除一个表。 首先打开控制台
$ rails c
然后将此命令粘贴到控制台
ActiveRecord::Migration.drop_table(:table_name)
将table_name替换为要删除的表。
您也可以直接从终端删除表。只需输入应用程序的根目录并运行此命令
$ rails runner "Util::Table.clobber 'table_name'"
Rails迁移drop_users 编辑迁移
class DropUsers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :name
t.timestamps
end
end
end
rake db: migrate
你可以按照指南中的方式回滚一次迁移:
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
通过这种方式,您还可以回滚并用于恢复任何迁移