Using UUIDv7 with Ruby on Rails Without PostgreSQL 18

2 pointsposted 9 hours ago
by t27duck

3 Comments

t27duck

9 hours ago

The app I work on at my day job uses UUIDs for primary keys. I'm not sure when/if an upgrade to PostgreSQL 18 will happen, but we wanted to take advantage of timestamp-based UUIDv7. Turns out, it's relatively easy to implement in current Rails with PostgreSQL < 18.

FBISurveillance

9 hours ago

Another option is to use `SecureRandom.uuid_v7` like this:

    # app/models/application_record.rb
    class ApplicationRecord < ActiveRecord::Base
      include PrimaryKeyGenerator
    end

    # app/models/concerns/primary_key_generator.rb
    module PrimaryKeyGenerator
      extend ActiveSupport::Concern

      included do
        after_initialize :generate_id
      end

      def generate_id
        return if self.class.attribute_types["id"].type != :uuid
        return if id.present?

        self.id ||= SecureRandom.uuid_v7
      end
    end

This also gives you the advantage of having your PK known before record persisted (maybe it's just me but I like my UUID PKs generated in app instead of db)

t27duck

8 hours ago

The big drawback is if your app also uses bulk sql inserts which bypasses model hooks. By letting the database handle it, all cases are covered.