Ruby on Rails: Avoiding infinite loop when calling .save during an update
I have an order model that has_many :items
. Each item has item.price
for the cost of said item. I want to add up all of the item prices in the order for a order.total_price
. Right now I'm doing that with
after_save :update_total_price, :if => "self.saved.nil? "
def update_total_price
self.total_price = Item.find(item_ids).inject(0){|sum,item| sum + (item.price * item.amount) } #amount is how many items there are
self.saved = 1
self.save if self.saved
end
This works just fine the first time that I put in the info, but if I try to edit the order, the total_price doesn't get updated because update_total_price
doesn't get called because self.saved is not nil.
What can I do to make it so that updating the model will update it, but won't keep on doing an infinite loop 开发者_如何学Pythonof calling .save
?
Why not have the update_total_price NOT save the data again.
just set the value in before_update:
before_save :update_total_price
def update_total_price
self.total_price = items.find(:all).inject(0){|sum,item| sum + (item.price * item.amount) }
end
after_save :update_total_price
def update_total_price
self.total_price = find_total_price
self.save_without_callbacks
end
def find_total_price
Item.find(item_ids).inject(0){|sum,item| sum + (item.price * item.amount)
end
精彩评论