Ruby on Rails:在更新期间调用 .save 时避免无限循环

发布于 2024-09-14 16:17:46 字数 618 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月打碎记忆 2024-09-21 16:17:46

为什么不让 update_total_price 不再保存数据。

只需在 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

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
时光沙漏 2024-09-21 16:17:46
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文