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
end