2. WHAT ISTRANSACTION ?
Rails transactions are a way to ensure
that a set of database operations will only
occur if all of them succeed. Otherwise,
they will rollback to the previous state of
data.
3. WHAT SHOULD WE USETRANSACTION?
An operation that affects more than a single database
row.
For example: Deposit, withdrawl from User, and create
Transfer log after.
Note that ActiveRecord::Base#save automatically opens
a transaction, so changes you make in callbacks, nested
attributes processing etc. will automatically run inside a
transaction.
4. CLASSIC EXAMPLE
The classic example is a transfer between two accounts
where you can only have a deposit if the withdrawal
succeeded and vice versa.
5. HOW DOES IT WORK?
Rails will open a transaction in the database engine, then start
executing the block.There are three possibilities:
1. If no exceptions occur during the block then Rails closes the
transaction and the database commits the data
2. If there is an exception, Rails will tell the database to cancel the
transaction and no data is changed
3. If the entire Rails process or server dies then the transaction
will timeout and be cancelled by the database
6. ROLLBACK
ROLLBACK returns the database to the state before the
transaction began.
Transactions will only rollback the transaction if an error is
raised.
The bang modifier (!) is a Rails convention for a method which
will throw an exception upon failure.
7. RAISING ROLLBACK
It is also possible to invalidate a transaction without raising
an exception that will propagate upwards by
using ActiveRecord::Rollback. This special exception allows
you to invalidate a transaction and reset the database
records without needing to rescue elsewhere in your code.