Last Updated: February 25, 2016
·
740
· jgtr

Create a random account id for a user

I want to create a unique ID for my user model (called account_id) that is not associated with the primary key. This ID will be provided to the user as another security measure for the user to identify their account.

Here are a few methods in the User model that were helpful in doing this.

Use this with an ActiveRecord callback (after initialize or before create) depending on your need.

after_initialize :assign_account_id

def assign_account_id
  possible_id = nil
  while possible_id.nil? || User.where(:account_id => possible_id).first
    possible_id = generate_id
  end
  self.account_id = possible_id
end

def generate_id
  id = ["A"]
  5.times{id<<SecureRandom.random_number(9)}
  id = id.join
end