[英]RAILS before_save callback of parent object runs before the associated child object is saved
我有一个Car类和一个Part类,如下所示。 这两个类均具有“价格”属性。 现在,汽车的价格是所有零件价格的总和。 同样,如果有零件没有价格,即如果汽车的一个或多个零件的价格为零,那么汽车的价格将设置为零。
Class Car
has_many :parts
before_save :calculate_price
private
def calculate_price
# calculate the price of car by summing all parts prices.
end
end
Class Part
belongs_to :car, inverse_of: parts
end
问题
每当零件的价格改变时,我想重新计算汽车的价格。 现在为此我添加了一个before_save回调,但是该回调在保存零件对象之前以及我执行self.parts
之前运行,它将从数据库中加载零件对象而不是从内存中加载它们,因此我无法获取价钱。 如何在关联的子对象已保存或从内存加载子对象之后使before_save运行?
您还需要在Part
模型中放置一个回调,因为您想对零件的价格变化做出反应,对吗? 就像是:
class Part
before_save :update_car_price
def update_car_price
self.car.touch if self.car.present?
end
end
未经测试,但我认为touch
应该足够,您不必暴露Car
的calculate_price
。
警告:如果您对汽车和零件进行大量价格更新,这可能会变得非常丑陋。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.