0

我有这样的代码:

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 失败,我希望回滚。但是没有回滚。我究竟做错了什么?

4

1 回答 1

1

I've had success with this pattern:

DataMapper::Model.raise_on_save_failure = true

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

Edit

Ok so you want to keep record of all errors before rolling back, then try something like this:

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
于 2013-06-23T14:15:54.617 回答