Q:

Rails 4: after_update callback leads to endless loop

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?

A:

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

