Skip to content

Commit 651cfbb

Browse files
committed
Add All or Nothing Database Transactions as a rails til.
1 parent 5e92101 commit 651cfbb

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
4141

4242
### rails
4343

44+
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
4445
- [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md)
4546
- [Attribute Was](rails/attribute-was.md)
4647
- [Capybara Page Status Code](rails/capybara-page-status-code.md)

Diff for: rails/all-or-nothing-database-transactions.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# All or Nothing Database Transactions
2+
3+
When you are updating multiple records in an *all or nothing* scenario, you
4+
can use [Active Record
5+
Transactions](http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html)
6+
to ensure that either everything is updated or none of it is updated.
7+
8+
For instance, if you are transferring *internet points* from one user's
9+
account to another user's account, you need to be sure that the transfer
10+
balances out. If updating one user is successful, but updating the other
11+
fails, then there will be a discrepancy in the data. A transaction will
12+
ensure that when any part of the update fails the entire transaction is
13+
rolled back (at the database level).
14+
15+
```ruby
16+
User.transaction do
17+
user1.internet_points += 20
18+
user2.internet_points -= 20
19+
user1.save!
20+
user2.save!
21+
end
22+
```

0 commit comments

Comments
 (0)