Reputation: 4848
I have two models: hotel and location. A location belongs to a hotel, a hotel has one location. I'm trying to create both in a single form, bear in mind that I can't use dm-nested for nested forms due to a dependency clash.
I have code that looks like:
if (@hotel.save && @location.save)
# process
else
# back to form with errors
end
Unfortunately, @hotel.save can fail and @location.save can complete (which confuses me because I didn't think the second condition would run in an AND block if the first one failed).
I'd like to wrap these in a transaction so I can rollback the Location save. I can't seem to find a way to do it online. I'm using dm-rails, rails 3 and a postgresql database. Thanks.
Upvotes: 0
Views: 181
Reputation: 1764
The usual way to wrap database operations in DataMapper is to do something like this:
@hotel.transaction do
@hotel.save
@location.save
end
Notice that @hotel
is quite arbitrary there; it could as well be @location
or even a model name like Hotel
.
In my experience, this works best when you enable exceptions to be thrown. Then if @hotel.save
fails, it will throw an exception, which will be caught by the transaction block, causing the transaction to be rolled back. The exception is, of course, reraised.
Upvotes: 1