skip to Main Content

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

?

2

Answers


  1. Solving it at the model level could be an option

    class MyModel < ApplicationRecord
      attribute :uuid, default: -> { "xxx_#{SecureRandom.uuid}" }
    end
    
    Login or Signup to reply.
  2. If you want a Postgres-specific solution, try this:

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

    (Postgres does string concatenation via ||, and recognises text in "ticks" (apostrophes) as being strings.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search