Transactions on Multiple Models

I can’t get transactions working correctly on multiple models.

I have an XML parser that’s importing a bunch of data into my system. I
have to update two different tables (models) but if anything at all
fails, I want it all rolled back. Here’s the code I’m using:

User.transaction do
Field.transaction do
user.update_attribute(“blah”, 1)
field.update_attribute(“other”, 2)

raise "test error"

end
end

Unfortunately, the call to update_attribute on the User model commits
even though the call on the Field model does not. This code also fails:

User.transaction do
user.update_attribute(“blah”, 1)

Field.transaction do
field.update_attribute(“other”, 2)

raise "test error"

end
end

Is there any way to do this such that ALL the DB calls will commit or
fail across multiple models?

Hello,
I know that this will come across as ‘flippant’, but, have you actually
-read- the update_attribute description ?

Note: This method is overwritten by the Validation module that?ll make
sure that updates made with this method doesn?t get subjected to
validation checks. Hence, attributes can be updated even if the full
object isn?t valid.

So, yes, from what -I- can see, update_attribute fires -instantly- and
its not really to be used ‘lightly’. Can I ask, whats wrong with saying
user.blah = 1 and then field.other = 2 ? I also doubt that your database
supports nested transactions, nor this is what you mean.

User.transaction do
user.blah = 1
field.other = 2

if field.save! and user.save! then
puts “everything hunky-dory”
end
end

No doubt, syntax isn’t precise, the moon isn’t in alignment or some
other reason that this will probably be wrong, so ymmv, but hopefully
you get the idea :wink: Fyi, the save! will also auto-raise an error on
failure, so, raising your own error isn’t required :wink:

Regards
Stef