# Puzzled about my Inventory manager counter

**URL:** <https://discuss.rubyonrails.org/t/puzzled-about-my-inventory-manager-counter/61609>\
**Category:** rubyonrails-talk\
**Created:** [November 14, 2011, 12:09pm UTC](https://discuss.rubyonrails.org/t/puzzled-about-my-inventory-manager-counter/61609 "2011-11-14T12:09:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brad\_W](https://avatars.discourse-cdn.com/v4/letter/b/b38774/32.png) [@Brad\_W](https://discuss.rubyonrails.org/u/Brad_W)\
**Post date:** [November 14, 2011, 12:09pm UTC](https://discuss.rubyonrails.org/t/puzzled-about-my-inventory-manager-counter/61609/1 "2011-11-14T12:09:00Z")

</div>

I have Product class which contains the attribute :quantity to keep track of how many of those I have in stock.

I have a Order class which has\_many Items, and the Item class also has an attribute :quantity to record how many of a product was ordered.

When an item is added to an order the Item.quantity is specified. This amount needs to be deducted from the Product.quantity. Not difficult.

When an item is deleted from an order, the Item.quantity needs to be added to the Product.quantity. Not difficult.

However, How would I go about re-adjusting the Product.quantity when an item.quantity is CHANGED?

It seems like it should be a trivial thing, but I'm not able to wrap my brain around it. Thanks for any help.

---

<div class="post-metadata">

**Author:** ![Frederick\_Cheung](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/frederick_cheung/32/3901_2.png) [@Frederick\_Cheung](https://discuss.rubyonrails.org/u/Frederick_Cheung)\
**Post date:** [November 14, 2011, 2:22pm UTC](https://discuss.rubyonrails.org/t/puzzled-about-my-inventory-manager-counter/61609/2 "2011-11-14T14:22:19Z")

</div>

You might want to use active record's change tracking. if you had an item, item.quantity\_changed? tells you whether the quantity has changed, item.quantity\_change returns an array where the first item is the old value, the second is the new value, item.changes is a hash of attribute names to pairs like that returned by quantity\_change.

Then if quantity has increased by 2, decrease Product.quantity by 2. You could do this in a before\_save or after\_save - this would ensure that is the save fails at some other point (e.g. the order fails some separate validation) all of the changes get rolled back. You should also be vary wary of race conditions - i'd look into using optimistic locking on the products table.

Fred
