rails-uuid-pk
Dead-simple UUIDv7 primary keys for modern Rails apps
Automatically use UUID v7 for all primary keys in Rails applications. Works with PostgreSQL, MySQL, and SQLite — zero configuration required. Just add the gem and you're done!
Why this gem?
- Uses native
SecureRandom.uuid_v7(Ruby 3.3+) - Automatically sets
:uuidas default primary key type - Works perfectly on PostgreSQL, MySQL, and SQLite
- Zero database extensions needed
- Production-ready logging for debugging and monitoring
Installation
Add to your Gemfile:
gem "rails-uuid-pk", "~> 0.11"Then run:
bundle installThat's it! The gem automatically enables UUIDv7 primary keys for all your models.
Usage
After installation, every new model automatically gets a uuid primary key with UUIDv7 values:
rails g model User name:string email:string
# → creates id: :uuid with automatic uuidv7 generation# This works out of the box:
User.create!(name: "Alice") # ← id is automatically a proper UUIDv7Opting Out of UUID Primary Keys
For specific models, you can opt out:
class LegacyModel < ApplicationRecord
use_integer_primary_key
# Uses integer auto-incrementing primary key instead of UUIDv7
end
# Migration must also use :integer
create_table :legacy_models, id: :integer do |t|
t.string :name
endMigration helpers automatically detect mixed primary key types and set appropriate foreign key types:
# Rails will automatically use integer foreign keys when referencing LegacyModel
create_table :related_records do |t|
t.references :legacy_model, null: false # → integer foreign key
t.references :user, null: false # → UUID foreign key (User uses UUIDs)
endImportant Compatibility Notes
Action Text & Active Storage
When installing Action Text or Active Storage, migrations automatically integrate with UUID primary keys - no changes needed.
Polymorphic associations
Polymorphic associations work seamlessly with UUID primary keys. Foreign key types are automatically detected.
Performance & Architecture
UUIDv7 provides excellent performance with monotonic ordering and reduced index fragmentation compared to UUIDv4.
- Generation: ~800,000 UUIDs/second with cryptographic security
- Storage: Native UUID (16B) on PostgreSQL, VARCHAR(36) on MySQL/SQLite
- Index Performance: Better locality than random UUIDs
For detailed performance analysis and optimization guides, see PERFORMANCE.md.
For architecture decisions and design rationale, see ARCHITECTURE.md.
Development
See DEVELOPMENT.md for setup instructions, testing, and contribution guidelines.
Security
For security considerations and vulnerability reporting, see SECURITY.md.
Contributing
Bug reports and pull requests welcome on GitHub. See DEVELOPMENT.md for contribution guidelines.
License
MIT License - see MIT-LICENSE for details.