devroom.io/drafts/2008-08-12-ruby-on-rails-uuid-as-your-activerecord-primary-key.md
Ariejan de Vroom dbae98c4c0 Moar updates
2013-03-24 14:27:51 +01:00

2.6 KiB

title kind slug created_at tags
Ruby on Rails: UUID as your ActiveRecord primary key article ruby-on-rails-uuid-as-your-activerecord-primary-key 2008-08-12
General

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.

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

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

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

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

sudo gem install uuidtools

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

require 'rubygems'
require 'uuidtools'

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

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

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

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?