Skip to content

Instantly share code, notes, and snippets.

@danielpaul
Created April 29, 2021 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpaul/161457dae829f8f7780f6131e353bcb6 to your computer and use it in GitHub Desktop.
Save danielpaul/161457dae829f8f7780f6131e353bcb6 to your computer and use it in GitHub Desktop.
Generate Unique User Referral Code
class User < ApplicationRecord
validates_length_of :first_name, :last_name, minimum: 2
validates :refferal_code, presence: true, uniqueness: true
before_validation :set_referral_code
private
def set_referral_code
return true if referral_code.present?
referral_code = new_referral_code
end
def new_referral_code
count = 0
token = nil
loop do
token = (first_name + last_name).upcase[0..2] + rand.to_s[2..5]
break if User.where(refferal_code: token).empty?
end
if count > 5
raise 'Took too long to generate a unique code'
end
token
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment