Maison > base de données > tutoriel mysql > le corps du texte

Rails执行数据库回滚时报错:ActiveRecord::IrreversibleMigration exceptio

WBOY
Libérer: 2016-06-07 16:45:22
original
830 Les gens l'ont consulté

最近在rails3.2下修改数据库表的字段,然后想回滚取消操作,但是在执行rake db:rollback命令时,出现错误:

最近在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   def change
    change_table :vm_temps do |t|
      t.change :disksize, :integer, :limit => 8
      t.change :mem_total, :integer, :limit => 8
    end
  end
end

上网查了资料,貌似原因在于对数据库表的字段类型进行修改时,数据库中的数据也会有变化,这样在回滚时不能修改这些变动的数据

《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   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的错误。

Ubuntu下Apache服务器安装以及使用Passenger插件部署Rails应用 

Ubuntu下搭建Ruby On Rails 

《Web开发敏捷之道应用Rails进行敏捷Web开发(原书第4版)》.((美)Sam Ruby).[PDF]+源代码 

Rails 的详细介绍:请点这里
Rails 的下载地址:请点这里

本文永久更新链接地址:

linux

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!