为什么Rails迁移失败?

时间:2020-10-05 06:33:40

标签: ruby-on-rails postgresql database-migration uuid

我使用uuid代替bigint作为主键。接下来的迁移

class CreateProjects < ActiveRecord::Migration[6.0]
  def change
    create_table :projects, id: :uuid do |t|
      t.string :title
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end

失败,并显示错误:

PG::DatatypeMismatch: ERROR:  foreign key constraint "fk_rails_b872a6760a" cannot be implemented
DETAIL:  Key columns "user_id" and "id" are of incompatible types: bigint and uuid.

1 个答案:

答案 0 :(得分:2)

t.references默认情况下假设另一个表具有一个bigint主键,并使外键字段也为bigint。添加外键后,就会显示此差异,并且迁移将失败。

使用type: :uuid指定该列的确应该由uuid填充。

t.references :user, null: false, foreign_key: true, type: :uuid

我自己在项目中通过记住每个引用/属于4种选择来跟踪它。 nullforeign_keytypeindex。即使我选择将其值保留为默认值,这也迫使我考虑这四个选项中的每一个。