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.

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

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.

Generate UUID in Ruby - SecureRandom Examples