ruby-on-railspostgresqlruby-on-rails-7pgcrypto

How can I override PostgreSQL's gen_random_uuid() in Rails?


I want to prepend a string to the uuid generated by PostgreSQL's gen_random_uuid() to use as the uuid for one of my models (it won't be the primary key).

Think like Stripe's price and customer ids - "price_xxxx..." and "cus_xxxx..."

Currently I'm using gen_random_uuid() like so:

t.uuid "uuid", default: -> { "gen_random_uuid()" }, null: false

Is it possible to do something like,

t.uuid "uuid", default: -> { "xxx" + "gen_random_uuid()" }, null: false

?


Solution

  • Solving it at the model level could be an option

    class MyModel < ApplicationRecord
      attribute :uuid, default: -> { "xxx_#{SecureRandom.uuid}" }
    end