0

I have such code:

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

I expect a rollback if any domain.save or vhost.save fails. But there is no rollback. What am I doing wrong?

ciembor
  • 7,189
  • 13
  • 59
  • 100

1 Answers1

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
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168