Vorleak Chy's Blog
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.
Subscribe-
Search-
Tags-
Categories-
Recent Comments-
- Using UUID as Primary Key in Ruby on Rails Thanks @Chamnap, I have...
- Using UUID as Primary Key in Ruby on Rails Not working. You need to...
- Installing GeoServer on Ubuntu Thanks for that! You saved me a lot...
- Change background color of TextBox or ComboBox in Windows Forms Hi....
- SQL Server 2005 Update Trigger Effect Multiple Rows Its really helpful...
2 people have left comments
Commentors on this Post-
- Copyright 2010 Vorleak Chy's Blog. All Rights Reserved. Powered by Wordpress | Theme designed by Chris Murphy
- Back To Top
- Home


Leave a Comment-