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.

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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值