Datamapper事务不回滚

时间:2013-06-23 13:27:03

标签: ruby transactions datamapper rollback

我有这样的代码:

Vhost.transaction do
  domains.each  do |domain| 
    unless domain.save
      errors << domain.errors
    end
  end
  unless vhost.save
    errors << vhost.errors
  end
end

如果任何domain.save或vhost.save失败,我预计会回滚。但是没有回滚。我做错了什么?

1 个答案:

答案 0 :(得分:1)

我在这种模式上取得了成功:

DataMapper::Model.raise_on_save_failure = true

MyModel.transaction do
  begin
    # do stuff
  rescue DataMapper::SaveFailureError
    t.rollback
  end
end

修改

好的,所以你想在回滚之前记录所有错误,然后尝试这样的事情:

Vhost.transaction do |t|
  new_errors = []

  domains.each  do |domain| 
    unless domain.save
      new_errors << domain.errors
    end
  end

  unless vhost.save
    new_errors << vhost.errors
  end

  errors += new_errors
  t.rollback if new_errors.any?
end