【问题标题】:Rails + Postgres Relation Issue With Custom Foreign KeyRails + Postgres 与自定义外键的关系问题
【发布时间】:2014-07-02 21:31:03
【问题描述】:

我正在从 MySQL 迁移到 Postgres,但遇到了一个我无法解决的问题。我敢肯定有简单的答案,但我被卡住了。

问题

我有一个 step 模型,它属于 template 模型,但指定了一个名为 template_uuid 的外键来匹配模板表 uuid 列。

这一切在 MySQL 上运行良好,但现在在 Postgres 上不起作用。调用 step.template 将返回相关模板,但现在它返回 nil

模板表的 uuid 列和步骤的 template_uuid 列都是 UUID 数据类型。

示例:

class Step < ActiveRecord::Base
 belongs_to    :template, :foreign_key => :template_uuid

所以,我在尝试调用关联时得到 nil

step = Step.last
step.template  => nil

但是,我可以使用 template_uuid 列查询模板,它工作得很好

Template.where(:uuid => step.template_uuid).first

所以..我在这里错过了什么。记录和 UUID 清楚地排列在一起,所以既然我使用的是 Postgres,为什么这种关系会破裂。数据库上没有物理外键,但这在以前并不重要。

有人有什么想法吗?

【问题讨论】:

    标签: mysql ruby-on-rails postgresql activerecord foreign-key-relationship


    【解决方案1】:

    我不能说它以前为什么有效,但是只要您在关联模型上还有一个自定义的 primary_key(除了 :id),您就必须提供它

      belongs_to :template, :primary_key => :uuid, :foreign_key => :template_uuid
    

    【讨论】:

    • 做到了。谢谢!我知道它必须是那样的小东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2015-12-02
    • 2013-07-27
    • 2021-04-04
    • 2021-12-12
    • 2019-02-09
    相关资源
    最近更新 更多