Code guide

Generate UUIDs in Ruby

Generate UUIDs in Ruby with SecureRandom.uuid, validate strings, and use UUIDs in Rails models.

Ruby ships UUID generation in its standard library through SecureRandom, so you rarely need a gem for version 4 identifiers.

Key takeaways

  • SecureRandom.uuid returns a version 4 UUID string.
  • No gem is required for basic generation.
  • Rails can use UUID primary keys with a database that supports them.

For implementation context, continue with UUID v4, SQL, and Database Guide. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

Generate a UUID

Require securerandom and call uuid. It uses a secure random source and returns the canonical lowercase form.

require "securerandom"

id = SecureRandom.uuid   # => "e5b7c1e2-..." version 4

UUIDs in Rails

With PostgreSQL you can make UUIDs the primary key type. Configure the generator so new models use UUIDs by default.

# config/application.rb
config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

Validate an incoming UUID v4 string

SecureRandom.uuid generates v4 values; it does not parse user input. For an endpoint that accepts only canonical UUID v4, check the full string, version digit and variant. Use Ruby absolute string anchors so a value followed by a newline cannot pass as a complete identifier.

This helper accepts uppercase letters and returns lowercase text. If the endpoint also accepts UUID v7 or special nil/max values, change the contract deliberately rather than silently accepting any UUID-shaped input.

UUID_V4 = /\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 normalize_uuid_v4(value)
  raise ArgumentError, "Invalid UUID v4" unless value.is_a?(String) && UUID_V4.match?(value)
  value.downcase
end

FAQ

Generate UUIDs in Ruby questions

Do I need a gem to generate UUIDs in Ruby?

No. SecureRandom.uuid in the standard library generates version 4 UUIDs without any gem.

Can Rails use UUID primary keys?

Yes, especially with PostgreSQL. Configure the generator and enable a UUID default in your migrations.

Does SecureRandom.uuid make v7?

It generates version 4. For UUID v7 use a maintained gem or your database.

Primary references

Standards and technical sources

The implementation and guidance on this page are checked against these standards and platform documentation sources.

Generate UUID in Ruby - SecureRandom Examples