How to Generate UUID in Ruby
- Ruby has built-in UUID generation — SecureRandom.uuid is in the standard library, no gem needed.
- SecureRandom.uuid returns a lowercase hyphenated UUID v4 string.
- Rails / ActiveRecord supports UUID primary keys natively with :uuid column type.
- PostgreSQL is the recommended database for UUID primary keys in Rails — use gen_random_uuid() as default.
- For UUID without dashes: SecureRandom.uuid.delete("-") or SecureRandom.hex(16).
Table of Contents
Ruby's standard library includes UUID generation via SecureRandom — no gem installation needed. For Rails applications, ActiveRecord has first-class UUID primary key support. This guide covers both the standard library approach and full Rails integration.
SecureRandom.uuid — Built-In UUID Generation
require 'securerandom'
# Generate UUID v4:
id = SecureRandom.uuid
puts id
# => "550e8400-e29b-41d4-a716-446655440000"
# It returns a new value every time:
puts SecureRandom.uuid == SecureRandom.uuid # => false (always different)
# UUID without dashes:
no_dashes = SecureRandom.uuid.delete("-")
# => "550e8400e29b41d4a716446655440000"
# Alternative — raw hex (same 32 chars, different random source):
hex = SecureRandom.hex(16)
# => "550e8400e29b41d4a716446655440000" (no version/variant bits set)
# Note: hex(16) does NOT produce a valid UUID — it is raw random hex
Important: SecureRandom.hex(16) produces 32 random hex characters but does NOT set the UUID version or variant bits — it is not a valid RFC 4122 UUID. Use SecureRandom.uuid for a proper UUID v4.
UUID Primary Keys in Rails (ActiveRecord)
# In config/application.rb — use UUID as default primary key type:
config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
# Migration — UUID primary key:
class CreateOrders < ActiveRecord::Migration[7.0]
def change
create_table :orders, id: :uuid do |t|
t.string :status, null: false
t.timestamps
end
end
end
# Migration with explicit default (PostgreSQL gen_random_uuid()):
create_table :orders, id: false do |t|
t.column :id, :uuid, primary_key: true, default: -> { "gen_random_uuid()" }
t.string :status
t.timestamps
end
With PostgreSQL, using gen_random_uuid() as the default lets the database generate the UUID — it works even when records are created outside Rails (e.g., via SQL scripts or data migrations).
UUID in ActiveRecord Model Configuration
# app/models/order.rb
class Order < ApplicationRecord
# Rails handles UUID primary keys automatically when :uuid column type is used
# No extra configuration needed
# Generate UUID before save if not set (for non-UUID-default databases):
before_create :set_uuid
private
def set_uuid
self.id ||= SecureRandom.uuid
end
end
# Usage:
order = Order.new(status: "pending")
order.save
puts order.id # => "550e8400-e29b-41d4-a716-446655440000"
# Find by UUID:
Order.find("550e8400-e29b-41d4-a716-446655440000")
# UUID in associations works automatically:
# Order belongs_to :customer (customer's id is also UUID)
class Order < ApplicationRecord
belongs_to :customer # foreign key is customer_id :uuid
end
Validate UUID Format in Ruby
UUID_REGEX = /A[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}z/i
def valid_uuid?(str)
UUID_REGEX.match?(str)
end
puts valid_uuid?("550e8400-e29b-41d4-a716-446655440000") # true
puts valid_uuid?("not-a-uuid") # false
# In Rails model validation:
class Order < ApplicationRecord
validate :valid_uuid_format
private
def valid_uuid_format
unless id.nil? || id.match?(UUID_REGEX)
errors.add(:id, "is not a valid UUID format")
end
end
end
# In a Rails controller — validate path parameter:
def show
unless params[:id].match?(UUID_REGEX)
render json: { error: "Invalid ID format" }, status: :bad_request
return
end
@order = Order.find(params[:id])
end
Use A and z anchors in Ruby instead of ^ and $ for string validation — in Ruby, ^ and $ match line boundaries, not string boundaries. A matches the start of the string and z matches the end.
UUID Gems for Advanced Use Cases
For most use cases, SecureRandom.uuid is sufficient. The gems below are useful for specific scenarios:
- uuidtools — generates v1, v3, v4, and v5 UUIDs. Use if you need UUID v5 (deterministic) without writing the hashing logic yourself.
- uuid7 — generates UUID v7 (time-ordered) for Rails applications needing sequential insert performance.
UUID7.generateproduces a v7 UUID.
# For UUID v5 with uuidtools:
# gem 'uuidtools'
require 'uuidtools'
namespace = UUIDTools::UUID.parse('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
id = UUIDTools::UUID.sha1_create(namespace, 'https://example.com/user/123')
puts id # Always the same for the same inputs
# For UUID v7:
# gem 'uuid7'
require 'uuid7'
id = UUID7.generate
puts id # Time-ordered UUID v7
Need a UUID for a Rails Seed File?
Generate 1 or 10 RFC-compliant UUID v4 values from the Cheetah UUID Generator — paste directly into db/seeds.rb or test fixtures.
Open Free UUID GeneratorFrequently Asked Questions
How do I generate a UUID in Ruby without any gems?
Use SecureRandom.uuid from the standard library — it is available in every Ruby installation since Ruby 1.9. No require beyond "securerandom".
Does SecureRandom.uuid generate UUID v4?
Yes. SecureRandom.uuid generates a UUID v4 (version 4, random) that is RFC 4122 compliant. The version and variant bits are set correctly.
How do I use UUID as a primary key in Rails with MySQL?
MySQL has no native UUID type. Use id: :string, limit: 36 or id: :binary, limit: 16 in your migration. Set the UUID default via a before_create callback in the model. PostgreSQL is the simpler choice for UUID primary keys in Rails.
Why use \A and \z instead of ^ and $ in Ruby UUID regex?
In Ruby, ^ and $ match line boundaries — a string with a newline could pass a ^ / $ anchored regex while containing invalid content. \A matches the absolute start of the string and \z matches the absolute end, making the validation secure.
Is SecureRandom.uuid thread-safe in Ruby?
Yes. SecureRandom uses a cryptographically secure random source (urandom on Unix, CryptGenRandom on Windows) that is safe to call from multiple threads simultaneously.

