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

150 views Asked by At

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

There are 2 answers

1
Arctodus On

Solving it at the model level could be an option

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

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.)