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 

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 

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?


mot
1.2k 声望16 粉丝

引用和评论

0 条评论