# 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•3h ago