views:

68

answers:

3

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!

+1  A: 
Simone Carletti
I believe UUID was already known by the asker (see the q. text) ;). But +1 for the third link.
Abel
A: 

Hi, i found this link, it looks quite interesting...

Creating small unique tokens in ruby

Rohan West
A: 

1) implement to_param in your models to modify the routing output.

def to_param
  magic(self.id)
end

2) implement the magic method (make sure it's a homomorphism - you need to be able to create a unmagic method)

A simple approach would be to multiply the number by a secret number, translate 0 -> a and use that. Reverse would be a -> 0 and division by your secret number and receive the real id

Marcel J.