Skip to content

Instantly share code, notes, and snippets.

@brycemcd
Created March 24, 2012 18:24
Show Gist options
  • Save brycemcd/2185876 to your computer and use it in GitHub Desktop.
Save brycemcd/2185876 to your computer and use it in GitHub Desktop.
For increment/decrement blog post
BEGIN;
UPDATE inventories SET inventory_amount = 99;
COMMIT;
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