Ruby on Rails:在更新期间调用 .save 时避免无限循环
我有一个 has_many :items
的订单模型。每个商品都有 item.price
来表示该商品的成本。我想将订单中的所有商品价格相加为 order.total_price
。现在我正在这样做,
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
第一次输入信息时效果很好,但如果我尝试编辑订单,total_price 不会更新,因为 update_total_price
不会更新被调用是因为 self.saved 不为零。
我该怎么做才能使更新模型会更新它,但不会继续执行调用 .save
的无限循环?
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 of calling .save
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不让 update_total_price 不再保存数据。
只需在 before_update 中设置值即可:
Why not have the update_total_price NOT save the data again.
just set the value in before_update: