Rails5—如何添加UUID列

Rails 5—How to add UUID column

在Rails 5中似乎没有太多关于UUID的文档。我找到的只是这段代码:

create_table :users, id: :uuid do |t|
  t.string :name
end

如果您要创建一个 table,那效果很好,但是如果您要更新一个已经存在的 table 怎么办?

如何添加 UUID 列到 table?

要从默认 ID 迁移到使用 uuid,请尝试像这样编写迁移:

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

以下是将 uuid 列添加到现有 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

如果您忘记添加 enable_extension 'uuid-ossp',您将收到以下错误:

PG::UndefinedFunction: ERROR: function uuid_generate_v4() does not exist ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: function uuid_generate_v4() does not exist