Created
March 24, 2012 18:24
-
-
Save brycemcd/2185876 to your computer and use it in GitHub Desktop.
For increment/decrement blog post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BEGIN; | |
UPDATE inventories SET inventory_amount = 99; | |
COMMIT; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def atomic_change(diff) | |
# gotta lock to prevent race conditions and stale reads | |
s = Model.find(self.id, :lock => true) | |
# sadly, we need to do our own error checking and validation using this method | |
# s.inventory_quantity SHOULD not be stale, but very well could be. Consider this a belt and | |
# suspenders approach | |
errors.add(:quantity, "cannot be negative!") and return false if s.quantity+ diff < 0 | |
#the update releases the lock above | |
Model.where(:id => self.id).update_all(["quantity = quantity + ?", diff]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment