I want to generate a token in my controller for a user in the \"user_info_token\" column. However, I want to check that no user currently has that token. Would this code suffice
The cleanest solution I found:
@seller.user_info_token = loop do
token = SecureRandom.urlsafe_base64
break token unless User.exists?(user_info_token: token)
end
And something very clean but with potential duplicates (very few though):
@seller.user_info_token = SecureRandom.uuid
Random UUID probability of duplicates
Edit: of course, add a unique index to your :user_info_token
. It will be much quicker to search for a user with the same token and it will raise an exception if by chance, 2 users are saved at the exact same moment with the exact same token!