将用户ID更改为UUID后迁移失败

时间:2019-01-28 01:19:55

标签: ruby-on-rails

我将用户ID更改为UUID,并修改了一些与user_id相关的表。但是对于某些表,例如流,我得到以下错误。有谁知道怎么走吗?

-- change_column(:streams, :user_id, :string)
   (18.1ms)  ALTER TABLE "streams" ALTER COLUMN "user_id" TYPE character varying
   (1.0ms)  ROLLBACK
   (1.3ms)  SELECT pg_advisory_unlock(740533580701532625)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DatatypeMismatch: ERROR:  foreign key constraint "fk_rails_bb64178f90" cannot be implemented
DETAIL:  Key columns "user_id" and "id" are of incompatible types: character varying and bigint.
: ALTER TABLE "streams" ALTER COLUMN "user_id" TYPE character varying

1 个答案:

答案 0 :(得分:0)

以下步骤有助于解决该问题:

class ConvertTableWithUserToString < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :uuid, :uuid, default: "gen_random_uuid()", null: false
    remove_foreign_key :streams, column: :user_id
    change_table :users do |t|
      t.remove :id
      t.rename :uuid, :id
    end
    execute "ALTER TABLE users ADD PRIMARY KEY (id);"
    change_column :streams, :user_id, :string
  end
end