在 Rails 中,如何创建将更改主键类型的迁移?

Dav*_*ave 4 migration postgresql uuid ruby-on-rails primary-key

我在 PostGres 中使用 Rails 4.2.7。我创建了几个表,所有表都有数字主键。下面是我的 Rails 迁移之一的示例

class CreateMyObjects < ActiveRecord::Migration
  def change
    create_table :my_objects do |t|
      t.string :name
      t.date :day
      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我在这个表中没有任何数据,但我有几个表通过外键链接到它。我想将主键从数字主键更改为 GUID (UUID),因为我将遇到在两个不同的数据库中创建数据的情况,并且我不希望在我时发生主键冲突结合数据。如何创建将主键的类型从数字更改为我的 UUID 类型的迁移,以及如何更新链接到表的所有外键?

谢谢, - 戴夫

And*_*eko 5

class ChangePrimaryKey < ActiveRecord::Migration
  def change
    remove_column :my_objects, :id # remove existing primary key
    add_column    :my_objects, :uuid, :string
    execute "ALTER TABLE my_objects ADD PRIMARY KEY (uuid);"
  end
end

class MyObject < ActiveRecord::Base
  self.primary_key = :uuid
end
Run Code Online (Sandbox Code Playgroud)

至于自动递增 - 不,Rails 不会id为你递增你的字符串,所以你必须自己处理它。

您可以before_create在模型中使用回调:

before_create :generate_uuid

  private

  def generate_uuid
    loop do
      self.uuid = SecureRandom.base64(16)         # or other way to generate uniq string
      break unless self.class.find_by(uuid: uuid) # make sure you don't repeat the uuid
    end
  end
Run Code Online (Sandbox Code Playgroud)

您还可以向 primary_key 列添加约束,例如not null约束uniquenesslength