Using UUID as Primary Key in Ruby on Rails

You may be working on multi-master database model which required to use UUID and sometime because of using auto incrementing integer primary key just is not good enough.

So, you want to replace the default integer-based primary keys in your model with a UUID.

Now you need to disable the default id column by setting :id => false and create a primary key named uuid instead

create_table :products, :id => false do |t|
  t.string :uuid, :limit => 36, :primary => true
end

In the Product model you need to set the name of this primary key column

class Product < ActiveRecord::Base
  set_primary_key "uuid"
end

You need to create UUID itself for the next step. Because of most databases do not support UUID out of the box so you have to do in rails application.

Install the uuidtools gem

sudo gem install uuidtools

Then go into your rails application and create uuid_helper.rb in your lib directory

require 'rubygems'
require 'uuidtools'

module UUIDHelper
  def before_create()
    self.uuid = UUIDTools::UUID.timestamp_create().to_s
  end
end

Include this module in all UUID-enabled models, like Product in this example

class Product < ActiveRecord::Base
  set_primary_key "uuid"
  include UUIDHelper
end

Now, you have the uuid field is automatically filled with a Universally Unique Identifier whenever you save a new Product object.

2 people have left comments

Chamnap - Gravatar

Chamnap said:

Not working. You need to move uuid_helper.rb in helper directory to lib directory.

Chamnap

Posted on: December 10, 2009 at 10:24 amQuote this Comment
Vorleak Chy - Gravatar

Vorleak Chy said:

Thanks @Chamnap, I have updated it.

Posted on: December 10, 2009 at 2:06 pmQuote this Comment

Leave a Comment-

Comment Guidelines: Basic XHTML is allowed (a href, strong, em, code). All line breaks and paragraphs are automatically generated. Off-topic or inappropriate comments will be edited or deleted. Email addresses will never be published. Keep it PG-13 people!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

All fields marked with "*" are required.