Using UUID as Primary Key in Ruby on Rails With MySQL Guide

Ruby on Rails MySQL UUID Primary Key Guide

A UUID (universally unique identifier) is an identifier standard used in software construction. A UUID is simply a 128-bit value. The meaning of each bit is defined by any of several variants.

For human-readable display, many systems use a canonical format using hexadecimal text with inserted hyphen characters. For example: de305d54-75b4-431b-adb2-eb6b9e546013.

The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination.

Installation
To use UUID as Primary Key you need to add uuidtools gem to your app’s Gemfile:

Gemfile
1
gem 'uuidtools'

Setting up UUID as Primary Key
To set UUID as Primary Key, you need to set id to false and the new UUID column as Primary Key in migration file:

*_create_products.rb
1
2
3
4
5
6
7
8
9
10
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products, id: false do |t|
      t.string :uuid, limit: 36, primary: true, null: false
      t.string :name, limit: 50, null: false

      t.timestamps
    end
  end
end

Inserting UUID Value into UUID Column
Create UUID helper library in app/lib directory:

uuid_helper.rb
1
2
3
4
5
6
7
8
9
10
11
module UuidHelper
  def self.included(base)
    base.primary_key = 'uuid'
    base.before_create :assign_uuid
  end

  private
  def assign_uuid
    self.uuid = UUIDTools::UUID.timestamp_create().to_s.upcase if uuid.blank?
  end
end

And then include UuidHelper library in Model file:

product.rb
1
2
3
class Product < ActiveRecord::Base
  include UuidHelper
end