Rails当你运行一个数据库回滚错误:ActiveRecord::IrreversibleMigration exception

最近rails3.2在更改数据库表字段,然后要回滚取消,但在运行rake db:rollback命令,错误:

rake aborted!
An error has occurred, all later migrations canceled:
ActiveRecord::IrreversibleMigration/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:42:in `block in inverse'

我的migration内容例如以下:

class ChangeVmTempColumns < ActiveRecord::Migration
def change
change_table :vm_temps do |t|
t.change :disksize, :integer, :limit => 8
t.change :mem_total, :integer, :limit => 8
end
end
end

上网查了资料,貌似原因在于假设在migration中做的数据类型转换是破坏性的时,就不能完毕回滚。

也就是说,对数据库表的字段类型进行改动时。数据库中的数据也会有变化,这样不能回滚这些变动的数据。

The migration that cannot be undone: Irreversible Migration》文章中举了一个样例:当我们在migration中change_column由integer变为string时是能够的,可是假设反过来。字段类型由string变为integer,我们就不能reverse
this migration。正好和我这样的情况一致!

*上,这个问题《ActiveRecord::IrreversibleMigration exception
when reverting migration
》提供了一个解决的方法:把self.change改为self.up和self.down方法。

改动后的migration:

class ChangeVmTempColumns < ActiveRecord::Migration
def self.up
change_table :vm_temps do |t|
t.change :disksize, :integer, :limit => 8
t.change :mem_total, :integer, :limit => 8
end
end def self.up
change_table :vm_temps do |t|
t.change :disksize, :string
t.change :mem_total, :string
end
end
end

运行rake db:rollback,成功!

原因:我原来觉得在Rails中,self.change方法直接把self.up和self.down两个综合在一起,运行和回滚仅仅用一个change方法就能够,可是经过这个样例,我觉得self.change方法运行回滚时。仅仅能採用默认的方式运行,一旦出现上述类型转换的问题就无法正常运行。可是self.down方法运行回滚时。会强制运行self.down声明,所以没有irreversible migration错误。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

上一篇:神经网络架构PYTORCH-几个概念


下一篇:js简易猜数字