AR Transactions

I have like 5-7 models in nested transactions like,

A.transaction do B.transaction do   C...   ... end end

It's mainly because I have to create has_many associated objects when I create a new object of A. Is this the best way to do it ?

Thanks, Pratik

You don't need to do nested transactions in Rails. Calling A.transaction is the same as calling B.transaction - it actually just goes to AR::Base.transaction, with nothing special on the table. Calling AR::Base.transaction is what starts the database transaction.

What you're probably interested in is also ensuring the integrity of the objects, instead of merely the database. In that case, pass the objects into the transaction method:

A.transaction(object_1, object_2, object_3) do   ... end

If the transaction fails, then the database won't be updated (of course), and object_1/2/3 will all revert to their state before the transaction.

Pat