I have the following code in my user model:
before_save :create_remember_token
private
def create_remember_token
generate_token(:remember_token)
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
This works well, but the trouble is that I was expecting it to fail. I was under the impression that the line: while User.exists?(column=>self[column]) would return false, since the record has not yet been saved to the db, and thus, the remember_token would not be set.
But newly created users do have their remember_token set, and I’m a little bit confused as to how this can be possible. Am I missing something?
In case anyone else is wondering, the code inside a
begin endexpression will run once before the condition is evaluated, unless you provide a rescue clause: