1. Reasons for using things
Ensure data consistency, and when a failure occurs, the operation can be rolled back
Like what:
activerecord::base.transaction do David.withdrawal (# withdrawal failure must trigger exception # deposit failure must trigger exceptionend
Return false does not start the operation rollback, so the thing to use! methods, such as save!. update!
Before_save such as callback are also contained in things, and if you want to trigger things to roll back, you need to be able to throw exceptions
If you do not want to rollback then do not throw an exception or put things outside the after_commit and other callbacl to deal with
Transaction traps
Do not catch Activerecord::recordinvalid exceptions inside the transaction. Because of some databases, this exception can cause transactions to fail, such as Postgres. Once the transaction is invalidated, the transaction must be re-executed from scratch for the code to work correctly.
In addition, when testing rollback or transaction rollback related callbacks, it is best to turn off the transactional_fixtures option, which is open in the general test framework.
Common transaction Anti-patterns
- Use transactions for single record operations
- Unnecessary use of nested transactions
- The code in the transaction does not cause a rollback
- Using transactions in the controller
Exception Handling and rolling back (to be translated)
Also the exceptions thrown within a transaction block would be propagated (after triggering the ROLLBACK) You should is ready-to-catch those in your application code.
One exception ActiveRecord::Rollback is the exception, which would trigger a ROLLBACK when raised, and not being re-raised by the transaction b Lock.
Warning: One should not catch ActiveRecord::StatementInvalid exceptions inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate, an Erro R occurred at the database level, for example when a unique constraint is violated. On some database systems, such as PostgreSQL, database errors inside a transaction cause the entire transaction to become Unusable until it ' s restarted from the beginning. Here's an example which demonstrates the problem:
#Suppose that we had a number model with a unique column called ' I '.number.transaction do number.create (i:0) Begin#This would raise a unique constraint error ...Number.create (i:0) Rescue Activerecord::statementinvalid#... which we ignore.End#On PostgreSQL, the transaction are now unusable. The following #statement'll cause a PostgreSQL error, even though the unique #constraint is no longer violated:Number.create (i:1) #= "PGError:ERROR:current transaction is aborted, commands #ignored until end of transaction block "End
Dealing with things in Rails