On my site, if a lot of people place orders at the same time, the
available quantity left in stock for a product seems to get wrong
every so often.
Here's my execute_purchase method, which is a before_filter on the
if product.quantity >= quantity # enough in stock
response = authorize_payment
product.update_attribute(:quantity, product.quantity -
raise FulfillmentError, response.message
raise FulfillmentError, "not enough in stock"
rescue FulfillmentError => e
So, I enter the transaction. Lock the product. I see if there's
enough in stock. If there's enough in stock, then I authorize the
payment -- if that's successful, then I decrement the available
quantity. Since I'm in a transaction and I've locked the record,
this method should be fine, right?
So, what happens is sometimes we sell more than we have. So, the
product quantity isn't always updated when an order happens.