Hi people
I have a doubt.
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
can somebody help me with this??
thanks
do you have some relation here?
eg
product
has_many :purchases
puchase (has column product_id)
belongs_to :product
and in purchase.rb
after_create :increase_product_purchase
def increase_product_purchase
product.increase_purchase
end
and in product.rb
def increase_purchase
update_attribute(:number_of_purchases, number_of_purchases + 1)
end
no, that's not what I'm looking for
product.quantity is the current amount of products
purchase.quantity is the amount of products I buy
so the new product.quantity should be the "old" product.quantity +
purchase.quantity
eg
current product.quantity = 5
purchase.quantity = 20
new product.quantity = 25
God,
def increase_product_purchase
product.increase_quantity(quantity)
end
in product
def increase_quantity(quantity)
update_attribute(:quantity, number_of_purchases + quantity)
end
or simply in purchase
def increase_product_purchase
product.update_attribute(:quantity, product.quantity + quantity)
end
?
Thanks for your help
The last option worked for me
def increase_product_purchase
product.update_attribute(:quantity, product.quantity + quantity)
end
it was pretty simple, but I couldn't figured out...
Thanks again