Ruby before_validation triggers infinite loop of c

2019-03-05 06:12发布

Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation will call. It giving SystemStackError: stack level too deep because self.save! triggers the before_validation. How to stop infinite loop of call back.

before_validation :method_1, :if => :recalculation_required_attribute

I am using optimistic locking using lock_version. 'update_all' will not increase the lock_version. So I am using save!. It is calling the infinite look of call back.

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

1条回答
Evening l夕情丶
2楼-- · 2019-03-05 06:25

You don't need self.save! there: you are already inside the transaction, so just do whatever you want to do and let Rails save the record once you are done.

Sidenotes:

  • Product.where(:id => self.id).update_all(attributes) probably could be rewritten as products.update_all(attributes) (having the association this_model has_many :products
  • self.attributes = attributes is redundant unless attributes is an instance method.
查看更多
登录 后发表回答