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 4UUIDs 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
endValidate 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