A database transaction groups a series of changes in such a way that either the database applies all of the changes or it applies none of the changes. The classic example of the need for transactions (and one used in Active Recordâs own documentation) is transferring money between two bank accounts. The basic logic is simple:
However, we have to be careful. What happens if the deposit succeeds but for some reason the withdrawal fails (perhaps the customer is overdrawn)? Weâll have added $100 to the balance in account1 without a corresponding deduction from account2. In effect, weâll have created $100 out of thin air.
Transactions to the rescue. A transaction is something ...