Rails 4: after_update callback leads to endless lo

2019-05-11 16:36发布

I use the after_update callback in my User model.

Model 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

However, this leads to an endless loop. The problem is that the callback is called again after self.save in the phone_validation method. phone_changed? apparently still returns true. How can I change this behaviour?

3条回答
倾城 Initia
2楼-- · 2019-05-11 16:54

In your case self.save triggers the update which triggers the after_update again ending in an endless loop.

Try giving before_update instead of after_update

before_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
查看更多
\"骚年 ilove
3楼-- · 2019-05-11 17:00

Try:

def phone_validation
  code = Array.new(8){rand(36).to_s(36)}.join
  self.update_column(phone_verification_code,code)
end

Hope it helps :)

查看更多
太酷不给撩
4楼-- · 2019-05-11 17:04

Try this:

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

OR

use with caution: skip callbacks

def phone_validation
 code = Array.new(8){rand(36).to_s(36)}.join
 self.update_column(:phone_verification_code => code)
end
查看更多
登录 后发表回答