There doesn't seem to be much documentation on UUID
s in Rails 5. All I've found is this code:
create_table :users, id: :uuid do |t|
t.string :name
end
That works great if you're creating a table, but what if you're updating an already-existing table?
How do you add a UUID
column to a table?
To migrate from default id to use uuid, try writing migration like this:
class ChangeProjectsPrimaryKey < ActiveRecord::Migration
def change
add_column :projects, :uuid, :uuid, default: "uuid_generate_v4()", null: false
change_table :projects do |t|
t.remove :id
t.rename :uuid, :id
end
execute "ALTER TABLE projects ADD PRIMARY KEY (id);"
end
end
Here's how to add a uuid
column to an existing Rails table.
class AddUuidToContacts < ActiveRecord::Migration[5.1]
def change
enable_extension 'uuid-ossp' # => http://theworkaround.com/2015/06/12/using-uuids-in-rails.html#postgresql
add_column :contacts, :uuid, :uuid, default: "uuid_generate_v4()", null: false
execute "ALTER TABLE contacts ADD PRIMARY KEY (uuid);"
end
end
If you forget to add enable_extension 'uuid-ossp'
, you'll get these errors:
PG::UndefinedFunction: ERROR: function uuid_generate_v4() does not exist ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: function uuid_generate_v4() does not exist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With