Rails 5—How to add UUID column

13,240

Solution 1

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

Solution 2

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

Share:
13,240
Mirror318
Author by

Mirror318

Coding between the lines. I'm living and loving Ruby on Rails, always learning and especially interested in software design/architecture. Outside of work I enjoy singing, cooking, electronics, and sunshine. I live, and yet not I but Christ that lives in me.

Updated on June 04, 2022

Comments

  • Mirror318
    Mirror318 almost 2 years

    There doesn't seem to be much documentation on UUIDs 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?

  • Mirror318
    Mirror318 over 7 years
    I got that, but it didn't work, the migration stops and shows this error: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'uuid DEFAULT 'uuid_generate_v4()' NOT NULL' at line 1: ALTER TABLE 'projects' ADD 'new_id' uuid DEFAULT 'uuid_generate_v4()' NOT NULL
  • januszm
    januszm about 7 years
    This doesn't work with MySQL. MySQL does not define function uuid_generate_v4 nor does it allow using function in DEFAULT (requires constant).
  • Robin
    Robin over 3 years
    You're assuming the OP is using PostgreSQL. He hasn't provided any information about it, but it appears he is actually using MySQL as he posted a MySQL error.