当部分迁移失败时,为什么不“撤消”?

时间:2013-10-01 01:40:36

标签: mysql ruby-on-rails activerecord migration

说我有这个迁移:

class MigrateStuff < ActiveRecord::Migration
  def up
    add_column :contacts, :receive_newsletter, :boolean, :default => false
    add_index :contacts, :receive_newsletter

    for t in SomeOtherThing.all
      #... do stuff in here
    end
  end

  def down
    #...
  end
end

所以我添加一个列和索引。然后我将一些数据添加到新列中。如果for循环中的某些部分失败,会发生什么?不删除列/索引。我尝试将此添加到事务中:

class MoveEmailRecipientsToContacts < ActiveRecord::Migration
  def up
    Volunteer.transaction do
      add_column :contacts, :receive_newsletter, :boolean, :default => false
      add_index :contacts, :receive_newsletter

      for t in SomeOtherThing.all
        #... do stuff in here
      end
    end
  end

  def down
    #...
  end
end

因此在for块中发生异常,这不会导致事务回滚吗?但是列和索引仍然存在!

处理此问题的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

另一种方法是通过引发ActiveRecord :: Rollback异常手动回滚。

raise ActiveRecord::Rollback

当您想要回滚时。

相关问题