Ruby on rails RAILS before_save父对象的回调在保存关联的子对象之前运行
我有一辆普通车和一个普通零件,如下所示。这两个类都有一个属性“price”。现在汽车的价格是所有零件价格的总和。此外,如果存在没有价格的零件,即如果汽车的一个或多个零件的价格为零,则汽车的价格设置为零Ruby on rails RAILS before_save父对象的回调在保存关联的子对象之前运行,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有一辆普通车和一个普通零件,如下所示。这两个类都有一个属性“price”。现在汽车的价格是所有零件价格的总和。此外,如果存在没有价格的零件,即如果汽车的一个或多个零件的价格为零,则汽车的价格设置为零 Class Car has_many :parts before_save :calculate_price private def calculate_price # calculate the price of car by summing all parts pr
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回调,但是回调在保存parts对象之前运行,当我执行
self.parts
时,它从数据库加载parts对象,而不是从内存加载它们,因此我不会得到price的更新值。如何在关联的子对象保存后运行before_save或从内存加载子对象?您还需要将回调放入零件
模型,因为您希望对零件的价格变化做出反应,对吗?比如:
class Part
before_save :update_car_price
def update_car_price
self.car.touch if self.car.present?
end
end
未测试,但我认为touch
应该足够了,而且您不必公开汽车的calculate\u price
警告:如果您对汽车和零件进行大量价格更新,这可能会变得非常糟糕。未测试-但请尝试将关联更改为“属于”:汽车,零件的反向,触摸:true。