【问题标题】:RAILS before_save callback of parent object runs before the associated child object is saved父对象的 RAILS before_save 回调在关联的子对象被保存之前运行
【发布时间】:2017-05-26 17:32:55
【问题描述】:

我有一个类 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?

【问题讨论】:

  • 未测试 - 但尝试将关联更改为 belongs_to :car, inverse_of: parts, touch: truemore information

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您还需要在Part 模型中添加回调,因为您想对零件的价格变化做出反应,对吧?比如:

class Part
  before_save :update_car_price

  def update_car_price
    self.car.touch if self.car.present?
  end
end

未测试,但我认为touch 应该足够了,您不必暴露Carcalculate_price

警告:如果您对汽车和零件进行大量价格更新,这可能会变得非常糟糕。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多