gpt4 book ai didi

ruby-on-rails - 外键 : belongs_to & has_one difference

转载 作者:数据小太阳 更新时间:2023-10-29 08:45:09 24 4
gpt4 key购买 nike

我不明白这两种关联类型的区别。

例如,我们有2张表:

拳击手

[ id, name, title ]

标题

[ id, name ]

所以,我们可以这样指定我们的关联:

boxer.rb

belongs_to :title, forign_key: "title"

然后像 Boxer.find(1).title.name 一样使用它

从逻辑上讲,每个拳手总是有一个冠军记录,每个冠军都有很多拳击手。

那么我们为什么不指定has_onehas_many 关系呢?当我指定 belongs_to :title, forign_key: "title" 时,这意味着 FK 点在我的例子中是 table 拳击手 (boxer.rb)。但是当我尝试编写 has_one :title, forign_key: "title" 时,它会在 titles 表中搜索 title 列。为什么?

最佳答案

您将具有外键索引的模型上的 belongs_to 放入另一个模型中。在另一个模型上,您放置了 has_one。两者都允许您覆盖 fk 列的名称,但它始终在带有 belongs_to 的表中。

我用这个技巧来记住:

belongs_to 他的主人(而不是相反),而主人 has_one 狗。这只狗佩戴着带有主人编号的 id 标签,而不是相反。

关于ruby-on-rails - 外键 : belongs_to & has_one difference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30719157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com