Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Add UUID Primary Key to Table in Database Already Using UUIDs as Primary Keys

In Rails 5.2, I have a has_and_belongs_to_many join table that I'm converting to a has_many :through relationship and so now need a primary key on the table.

I'm already using UUIDs as primary keys in my Postgres database and so I need to add a UUID primary key column but can't get the syntax right.

I've tried...

add_column :products_uw_questions, :uuid, :primary_key

but that just created an integer-based column.

I also tried...

add_column :products_uw_questions, :id, :primary_key

thinking the UUID settings already in place would take care of it, but no luck.

What's the correct syntax if I the database is already using UUID primary keys?

like image 397
Travis Smith Avatar asked Jan 26 '26 22:01

Travis Smith


1 Answers

Kept trying until this worked...

def change
  add_column :products_questions, :id, :uuid, primary_key: true, default: -> { "gen_random_uuid()" }
end
like image 104
Travis Smith Avatar answered Jan 29 '26 10:01

Travis Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!