【问题标题】:Primary key and foreign key out of range主键和外键超出范围
【发布时间】:2018-08-27 04:32:15
【问题描述】:

我有一个人物模型:

id: int, uuid:bigint

还有一篇博文:

id: int, uuid:bigint, person_id: int

我希望 blogpost.person 返回人物模型的 uuid,而不是他们的 id。

我试过(个人类):

has_many :blogposts, dependent: :delete_all, inverse_of: :deck, primary_key: :uuid

然后我得到:

ActiveModel::RangeError: 1534420711008 is out of range for ActiveModel::Type::Integer with limit 4 bytes.

任何帮助将不胜感激。

【问题讨论】:

标签: ruby-on-rails postgresql foreign-keys rails-activerecord


【解决方案1】:

您已将外键 person_id 定义为 int,但您试图让它将关联的 bigint uuid 存储在 int 字段中。尝试在您的架构中使用 bigint for person_id

这是假设您已将 uuid 设置为 Person 的主键。如果你还没有:https://edgeguides.rubyonrails.org/active_record_basics.html#overriding-the-naming-conventions

编辑

正如您所说,您不想将 uuid 设为 person 的主键。外键通常引用另一个表中的主键,但也可以引用唯一索引列。

首先,按照惯例,blogpost.person 不应返回 uuid,而应返回 Person 对象。因此,简单的方法是添加范围或方法:

class Blogpost < ApplicationModel

  def person
    Person.find_by_uuid(person_uuid)
  end

end

其次,如果 blogpost.person_id 字段包含 uuid,则它应该 (1) 是 bigint,而不是 int,并且 (2) 为了您的理智重命名为 person_uuid,如上面的例子。如果这就是您需要的所有逻辑,那么该解决方案应该可以正常工作(假设 uuid 列是 Person 中的唯一索引)。您还可以将其定义为适当的外键关系:

class Blogpost < ApplicationModel
  belongs_to :person, foreign_key: :person_uuid
end

class Person < ApplicationModel
  has_many :blogposts, foreign_key: :person_uuid, inverse_of: :person, primary_key: :uuid
end

但是,如果 person_uuiduuid 不是主键,请确保将它们定义为迁移中的唯一索引。 (unique: true 在列定义中)

【讨论】:

  • 感谢您的努力,但我不希望 person 的主键是它的 uuid。我宁愿让博客对象上的 person_id 字段简单地引用一个人的 uuid 字段。这不可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 2020-02-06
  • 2015-02-04
  • 2020-07-07
相关资源
最近更新 更多