Best way to create unique token in Rails?


# app/models/model_name.rb
class ModelName < ActiveRecord::Base
  include Tokenable
end

# app/models/concerns/tokenable.rb
module Tokenable
  extend ActiveSupport::Concern

  included do
    before_create :generate_token
  end

  protected

  def generate_token
    self.token = loop do
      random_token = SecureRandom.urlsafe_base64(nil, false)
      break random_token unless self.class.exists?(token: random_token)
    end
  end
end

and in devise
https://github.com/plataformatec/devise/blob/v3.4.1/lib/devise/models/rememberable.rb#L118


# Generate a token checking if one does not already exist in the database.
def remember_token #:nodoc:
  loop do
    token = Devise.friendly_token
    break token unless to_adapter.find_first({ remember_token: token })
  end
end

你可能感兴趣的:(Best way to create unique token in Rails?)