UUID V7 for Ruby on Rails

Introduction

uuid_v7 is a RubyGem specifically designed to provide UUID V7 support for Mysql and Sqlite databases in Ruby on Rails applications. This gem is particularly useful because these databases lack a native type for supporting UUIDs.

Note: PostgreSQL users do not require this gem as PostgreSQL supports UUID natively.

Features

  • Converts UUID V7 CHAR(36) to a more efficient CHAR(32) and stores it in BINARY(16) for performance enhancement.
  • Integrates seamlessly with ActiveRecord::Base, enabling UUID as the primary key for models.
  • Migration helper for easy transition to UUIDs in existing Rails applications, specifically tailored for Mysql.

Installation

Add this line to your application's Gemfile:

gem 'uuid_v7'

And then execute:

bundle install

Or install it yourself as:

gem install uuid_v7

Usage

Basic Setup

Once installed, uuid_v7 extends ActiveRecord::Base to use UUID as the primary key.

Foreign Keys

Declare foreign key associations in your models as follows:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  attribute :author_id, :uuid_v7
  belongs_to :author
end

Configuration

Custom Primary Key

If your primary key is not :id, run:

rails generate uuid_v7:install

And configure:

UuidV7.configure do |config|
  config.field_name = :uuid
end

Implicit Inclusion Strategy

By defaut the primary key type is overrided, if you want to prevent that behaviour toogle the strategy.

in config/initializers/uuid_v7.rb`

UuidV7.configure do |config|
  config.implicit_inclusion_strategy = false
end

Then add manually to the model you want.

class Author < ActiveRecord::Base
  attribute :id, :uuid_v7, default: -> { SecureRandom.uuid_v7 }

  has_many :books
end

Recommendation: It's advised to use :id as the primary key with Rails for compatibility and convention.

Migrations

Helper for Mysql

uuid_v7 provides a migration helper for Mysql. To add a UUID field to a model, run:

rails generate migration AddUuidToUser uuid:binary

Then use the helper in your migration file:

class AddUuidToUser < ActiveRecord::Migration[7.1]
  def change
    # Add the field :uuid
    populate_uuid_field(table_name: :users, column_name: :uuid)
  end
end

Custom Migration Template

To override the default :id implementation in new migrations:

rails generate uuid_v7:migrations

A modified migration template will be available under lib/templates/active_record/migration/create_table_migration.rb.

Example of a generated model migration:

class AddAuthor < ActiveRecord::Migration[7.1]
  def change
    create_table :authors, id: false do |t|
      t.binary :id, limit: 16, null: false, index: { unique: true }, primary_key: true
      t.string :name
      t.timestamps
    end
  end
end

Contributing

Bug reports and pull requests are welcome on GitHub at [https://github.com/alliantist/uuid_v7].