Last updated

Ruby on Rails: UUID as your ActiveRecord primary key

Sometimes, using the good old ‘auto increment’ from your database just isn’t good enough. If you really require that all your objects have unique ID, even across systems and different databases there’s only one way go: UUID or Universally Unique IDentifier.

A UUID is generated in such a way that every generated UUID in the world is unique. For example: 12f186e6-687e-11ad-843e-001b632783f1. This string is randomly generated based on several factors that guarantee it’s uniqueness.

Anyway, you want to replace the default integer-based primary keys in your model with a UUID. This is quite easy, but there are some caveats.

First off, you should have a column in your database table that holds the UUID. You may be tempted to just change the column definition for id from integer to string and be done with it. But this won’t work as expected. For your development, and maybe even your production system, this may work fine, but you might be in for some unexpected surprises.

The best example of such a surprise is RSpec. RSpec uses ‘rake db:schema:dump’ to create a sql dump to quickly load the database with. However, the ‘schema:dump’ does not look at the id column in your database, but instead adds the default primary key definition from the ActiveRecord adapter.

The solution is to disable the id column and create a primary key column named uuid instead.

1create_table :posts, :id => false do |t|
2  t.string :uuid, :limit => 36, :primary => true
3end

In your Post model you should then set the name of this new primary key column.

1class Post < ActiveRecord::Base
2  set_primary_key "uuid"
3end

The next step is to create the UUID itself. We’ll have to do this the Rails app, because most databases don’t support UUID out of the box.

First install the uuidtools gem

1sudo gem install uuidtools

Create a file like lib/uuid_helper.rb and add the following content.

1require 'rubygems'
2require 'uuidtools'
3
4module UUIDHelper
5  def before_create()
6    self.uuid = UUID.timestamp_create().to_s
7  end
8end

Then, include this module in all UUID-enabled models, like Post in this example.

1class Post < ActiveRecord::Base
2  set_primary_key "uuid"
3  include UUIDHelper
4end

Now, when you save a new Post object, the uuid field is automatically filled with a Universally Unique Identifier. What else could you wish for?

Tags: General