【问题标题】:Why Rails Migration fails?为什么 Rails 迁移失败?
【发布时间】:2021-01-20 00:21:09
【问题描述】:

我使用 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.

【问题讨论】:

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


【解决方案1】:

t.references 默认情况下假定另一个表有一个bigint 主键,并使外键字段也是一个bigint。一旦添加了外键,就会发现这种差异并且迁移失败。

使用type: :uuid 指定列确实应该是uuid

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

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

【讨论】:

  • 你是我的英雄!谢谢
猜你喜欢
  • 1970-01-01
  • 2011-10-31
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
相关资源
最近更新 更多