On Nov 14, 12:09 pm, Brad W <[email protected]> wrote:
> 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.

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

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to