zoukankan      html  css  js  c++  java
  • 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。正好和我这样的情况一致!

    Stackoverflow上,这个问题《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错误。

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

  • 相关阅读:
    转:matplotlib画图,plt.xx和ax.xx之间有什么差异
    转:Python __call__()方法,可调用对象
    训练集,验证集,测试集,交叉验证
    Visio画图和导出图的时候,去除多余白色背景
    在线jupyter notebook
    dfs序
    codeforces 877b
    codeforce864d
    codeforce868c
    查看本地git查看git公钥,私钥的方式
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4622601.html
Copyright © 2011-2022 走看看