Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all. Example:
This example will only take money from David and give to Mary if neither withdrawal nor deposit raises an exception. Exceptions will force a ROLLBACK that returns the database to the state before the transaction was begun. Be aware, though, that the objects by default will not have their instance data returned to their pre-transactional state.
Different ActiveRecord classes in a single transaction
Though the transaction class method is called on some ActiveRecord class, the objects within the transaction block need not all be instances of that class. In this example a Balance record is transactionally saved even though transaction is called on the Account class:
Transactions are not distributed across database connections
A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. One workaround is to begin a transaction on each class whose models you alter:
This is a poor solution, but full distributed transactions are beyond the scope of Active Record.
Save and destroy are automatically wrapped in a transaction
Both Base#save and Base#destroy come wrapped in a transaction that ensures that whatever you do in validations or callbacks will happen under the protected cover of a transaction . So you can use validations to check for values that the transaction depends on or you can raise exceptions in the callbacks to rollback.
Exception handling
Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you should be ready to catch those in your application code. One exception is the ActiveRecord::Rollback exception, which will trigger a ROLLBACK when raised, but not be re-raised by the transaction block.
In an application I wrote for a client I needed transactions to handle a batch import of records from a legacy table into different models.
I browsed the documentation, googled for info and even asked in #rubyonrails, but wasn’t able to get any help, so I had to resort to good old trial and error.
First I tried nested transactions (the old way):
I had a couple of problems with this code:
- Ugly
- Deprecated
It also didn’t seem to work for me, so I banged my head against my laptop for half a hour or so and suddenly the rails documentation started to make sense, so I wrote this code instead:
The reason I used save! was that the documentation says that a transaction block catches exceptions. Unfortunately that’s not true and to make it work I had to remove the exclamation marks.
Now I had another problem. I included the transaction code in a class I put in lib/, ImportJob, and I was using it with script/runner:
All of a sudden I started getting method missing errors on transaction. Now I could investigate and do the right thing or just hack a solution – I decided to hack a solution
Deriving ImportJob from Migration solved my problems. Now if anyone has a cleaner solution I will be happy to implement it but at least I solved my problem with transactions (and I hope this will be helpful for someone else too).
Update: Tim pointed out some flaws in my code and some more testing revealed that I needed to have an exception to trigger a Rollback, so I modified the block:
转自:http://tempe.st/2007/05/transaction-in-rails/