我使用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.
答案 0 :(得分:2)
t.references
默认情况下假设另一个表具有一个bigint
主键,并使外键字段也为bigint
。添加外键后,就会显示此差异,并且迁移将失败。
使用type: :uuid
指定该列的确应该由uuid
填充。
t.references :user, null: false, foreign_key: true, type: :uuid
我自己在项目中通过记住每个引用/属于4种选择来跟踪它。 null
,foreign_key
,type
和index
。即使我选择将其值保留为默认值,这也迫使我考虑这四个选项中的每一个。