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
I have many models I apply unique tokens to. For this reason I've created a Tokened
concern in app/models/concerns/tokened.rb
module Tokened
extend ActiveSupport::Concern
included do
after_initialize do
self.token = generate_token if self.token.blank?
end
end
private
def generate_token
loop do
key = SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')
break key unless self.class.find_by(token: key)
end
end
end
In any model I want to have unique tokens, I just do
include Tokened
But yes, your code looks fine too.