Hacker News new | ask | show | jobs
by FBISurveillance 217 days 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)
1 comments

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.