Rails当你运行一个数据库回滚错误:ActiveRecord::IrreversibleMigration exception
我的migration內(nèi)容例如以下:
class ChangeVmTempColumns < ActiveRecord::Migrationdef changechange_table :vm_temps do |t|t.change :disksize, :integer, :limit => 8t.change :mem_total, :integer, :limit => 8endend end上網(wǎng)查了資料,貌似原因在于假設在migration中做的數(shù)據(jù)類型轉(zhuǎn)換是破壞性的時,就不能完畢回滾。
也就是說,對數(shù)據(jù)庫表的字段類型進行改動時。數(shù)據(jù)庫中的數(shù)據(jù)也會有變化,這樣不能回滾這些變動的數(shù)據(jù)。
《The migration that cannot be undone: Irreversible Migration》文章中舉了一個樣例:當我們在migration中change_column由integer變?yōu)閟tring時是能夠的,可是假設反過來。字段類型由string變?yōu)閕nteger,我們就不能reverse this migration。正好和我這樣的情況一致!
Stackoverflow上,這個問題《ActiveRecord::IrreversibleMigration exception when reverting migration》提供了一個解決的方法:把self.change改為self.up和self.down方法。
改動后的migration:
class ChangeVmTempColumns < ActiveRecord::Migrationdef self.upchange_table :vm_temps do |t|t.change :disksize, :integer, :limit => 8t.change :mem_total, :integer, :limit => 8endenddef self.upchange_table :vm_temps do |t|t.change :disksize, :stringt.change :mem_total, :stringendend end
運行rake db:rollback,成功!
原因:我原來覺得在Rails中,self.change方法直接把self.up和self.down兩個綜合在一起,運行和回滾僅僅用一個change方法就能夠,可是經(jīng)過這個樣例,我覺得self.change方法運行回滾時。僅僅能採用默認的方式運行,一旦出現(xiàn)上述類型轉(zhuǎn)換的問題就無法正常運行。可是self.down方法運行回滾時。會強制運行self.down聲明,所以沒有irreversible migration錯誤。
版權(quán)聲明:本文博客原創(chuàng)文章,博客,未經(jīng)同意,不得轉(zhuǎn)載。
總結(jié)
以上是生活随笔為你收集整理的Rails当你运行一个数据库回滚错误:ActiveRecord::IrreversibleMigration exception的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Sql语句之select 5种查询
- 下一篇: 对正在运行的mysql进行监控