博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ruby on Rails: UUID as your ActiveRecord primary key
阅读量:6806 次
发布时间:2019-06-26

本文共 2179 字,大约阅读时间需要 7 分钟。

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 => trueend

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  endend

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?

转载地址:http://lyhwl.baihongyu.com/

你可能感兴趣的文章
Linux一些有用的操作
查看>>
IAT 注入ImportInject(dll)
查看>>
[C++]面向对象部分——类
查看>>
Websense:别让移动设备触痛企业的安全神经
查看>>
DHCP服务的介绍及配置详解
查看>>
脚本实现为一系列账号生成随机密码
查看>>
mysql高级管理-note
查看>>
linux登录显示 Error in service module错误
查看>>
娱乐篇第十期:互联网的事情you意思(十)
查看>>
MyBatis基础:MyBatis入门(1)
查看>>
Linux文件的复制、删除和移动命令
查看>>
vmware workstation虚拟环境安装及创建虚拟机
查看>>
360搜索引擎能否给苦逼的站长们带来希望?
查看>>
yarn管理命令
查看>>
SSH KEY免密码验证
查看>>
我的友情链接
查看>>
客户端判断是否为IE9以上版本
查看>>
newusers和chpasswd的用法
查看>>
电信商务领航1-1端口映射即虚拟服务器
查看>>
关键字AUTO_INCREMENT 重命名表 修改列的属性。
查看>>