Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique random string for identifying a record

I have a requirement to be able to identify a record in a table, in this case a user table, by a unique key which does not give away the ordering of the records in the table.

Currently I have primary key field and the routes that are generated look like:

/users/1

However, I'd like to be able to generate a route like:

/users/kfjslncdk

I can wire everything up on the route side, database side etc.. but I'm not sure what the best way to generate a unique string identifier would be in rails. I'd like do something like:

before_save :create_unique_identifier

def create_unique_identifier
    self.unique_identifier = ... magic goes here ...
end

I was thinking I could use the first part of a guid created using UUIDTools, but I'd need to check to make sure it was unique before saving the user.

Any advice would be greatly appreciated!

like image 357
jonnii Avatar asked Nov 29 '09 00:11

jonnii


People also ask

How do you generate random unique strings in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


2 Answers

before_create :create_unique_identifier

def create_unique_identifier
  loop do
    self. unique_identifier = SecureRandom.hex(5) # or whatever you chose like UUID tools
    break unless self.class.exists?(:unique_identifier => unique_identifier)
  end
end
like image 118
Aditya Sanghi Avatar answered Sep 21 '22 21:09

Aditya Sanghi


Ruby 1.9 includes a built-in UUID generator: SecureRandom.uuid

like image 42
NARKOZ Avatar answered Sep 22 '22 21:09

NARKOZ