我在User模型中使用了after_update回调. 型号User.rb after_update :check_phonecheck_phone phone_validation if phone_changed?enddef phone_validation code = Array.new(8){rand(36).to_s(36)}.join self.phone_verification_code = code sel
型号User.rb
after_update :check_phone check_phone phone_validation if phone_changed? end def phone_validation code = Array.new(8){rand(36).to_s(36)}.join self.phone_verification_code = code self.save end
然而,这导致无限循环.问题是在phone_validation方法中的self.save之后再次调用回调. phone_changed?显然仍然是真的.我该如何改变这种行为?
试试这个:User.rb
attr_accessor :phone_checked after_update :check_phone, :unless => "phone_checked" check_phone phone_validation if phone_changed? end def phone_validation code = Array.new(8){rand(36).to_s(36)}.join self.phone_verification_code = code self.phone_checked = true # update flag self.save end
要么
谨慎使用:skip callbacks
def phone_validation code = Array.new(8){rand(36).to_s(36)}.join self.update_column(:phone_verification_code => code) end