mirror of
https://github.com/jbranchaud/til
synced 2026-01-06 16:48:01 +00:00
Add All or Nothing Database Transactions as a rails til.
This commit is contained in:
@@ -41,6 +41,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
|
||||
### rails
|
||||
|
||||
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
|
||||
- [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md)
|
||||
- [Attribute Was](rails/attribute-was.md)
|
||||
- [Capybara Page Status Code](rails/capybara-page-status-code.md)
|
||||
|
||||
22
rails/all-or-nothing-database-transactions.md
Normal file
22
rails/all-or-nothing-database-transactions.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# All or Nothing Database Transactions
|
||||
|
||||
When you are updating multiple records in an *all or nothing* scenario, you
|
||||
can use [Active Record
|
||||
Transactions](http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html)
|
||||
to ensure that either everything is updated or none of it is updated.
|
||||
|
||||
For instance, if you are transferring *internet points* from one user's
|
||||
account to another user's account, you need to be sure that the transfer
|
||||
balances out. If updating one user is successful, but updating the other
|
||||
fails, then there will be a discrepancy in the data. A transaction will
|
||||
ensure that when any part of the update fails the entire transaction is
|
||||
rolled back (at the database level).
|
||||
|
||||
```ruby
|
||||
User.transaction do
|
||||
user1.internet_points += 20
|
||||
user2.internet_points -= 20
|
||||
user1.save!
|
||||
user2.save!
|
||||
end
|
||||
```
|
||||
Reference in New Issue
Block a user