Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning Each User a Unique 100 character Hash in Ruby on Rails

I have a form on a website that takes in some personal information from the visitor. I'm passing this information to another service and I need to assign each one of these form submits a 100 character unique hash to be stored in the DB with the record. What's the optimal way to generate this key and make sure it's unique? It's okay if the key auto-increments.

like image 938
Splashlin Avatar asked Jan 24 '10 00:01

Splashlin


2 Answers

ActiveSupport::SecureRandom.hex(50)

The chance of this not being unique is astronomical.

Alternate simple "does not scale" race condition fail solution.

class MyModel < ActiveRecord::Base
  before_create :assign_unique_token

  private

  def assign_unique_token
    self.unique_token = ActiveSupport::SecureRandom.hex(50) until unique_token?
  end

  def unique_token?
    self.class.count(:conditions => {:unique_token => unique_token}) == 0
  end
end

If you really want to make sure, make an unique index on the column, and handle a DB uniqueness error by retrying, similar to my implementation above.

like image 107
August Lilleaas Avatar answered Oct 25 '22 23:10

August Lilleaas


The Ruby standard lib has a module for generating GUIDs:

http://ruby-doc.org/stdlib/libdoc/digest/rdoc/classes/Digest/SHA2.html

Example:

Digest::SHA1.hexdigest(Time.now.to_s)
like image 35
tfwright Avatar answered Oct 26 '22 00:10

tfwright