I have 2 tables (models) “Product” and “Purchase”. I want to use the
callback after_create to update the attribute Product.quantity every
time a Purchase is created, so I think this should be work, but I
don’t know the right syntax
In purchase model
def after_create
Product.update(product.quantity = product.quantity +
purchase.quantity)
end
def after_create
product.update_attribute(:quantity, product.quantity + quantity)
end
and it works fine, but now I’m trying to do something else with the
update. I mean, sometimes you can input some wrong data, so you need
to update values. So I was thinking in update the purchase.quantity
and then automagically update the product.quantity, so I tried this
def before_update
product.update_attribute(:quantity, product.quantity -
purchase.quantity)
end
def after_update
product.update_attribute(:quantity, product.quantity +
purchase.quantity)
end
but, that didn’t work, in both cases purchase.quantity is the new
value, and I need in the first case (before_update) the original value
and in the second case (after_update) the new value for
purchase.quantity