Ruby before_validation 触发回调无限循环

Ruby before_validation triggers infinite loop of call back

产品型号有 attribute_1。如果 attribute_1 需要重新计算,则 before_validation 将调用。它给出 SystemStackError: stack level too deep 因为 self.save! 触发了 before_validation。如何停止回调的无限循环。

before_validation :method_1, :if => :recalculation_required_attribute

我正在使用 lock_version 使用乐观锁定。 'update_all'不会增加lock_version。所以我使用 save!。是在召唤无限的回望。

def method_1
    ####
    ####
    if self.lock_version == Product.find(self.id).lock_version
       Product.where(:id => self.id).update_all(attributes)
       self.attributes = attributes
       self.save!
    end
end

你不需要self.save!那里:你已经在交易中,所以只要做你想做的,完成后让Rails保存记录。

旁注:

  • Product.where(:id => self.id).update_all(attributes) 可能可以重写为 products.update_all(attributes)(关联 this_model has_many :products
  • self.attributes = attributes 是多余的,除非 attributes 是实例方法。