Travis Smith
Travis Smith

Reputation: 632

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?

Upvotes: 2

Views: 786

Answers (1)

Travis Smith
Travis Smith

Reputation: 632

Kept trying until this worked...

def change
  add_column :products_questions, :id, :uuid, primary_key: true, default: -> { "gen_random_uuid()" }
end

Upvotes: 4

Related Questions