【问题标题】:Ruby on Rails belongs_to vs. has_one associations - clarification requestedRuby on Rails 的 belongs_to 与 has_one 关联 - 要求澄清
【发布时间】:2013-08-21 17:26:53
【问题描述】:

在下面的例子中,在 Chlid 类中使用 belongs_to :mother 和 has_one :mother 有什么区别?我一直在阅读有关这方面的 Rails 文档,除了阅读它所涉及的语义之外,我看不出任何一个会产生什么不同。

据我所知,各种关联为每个类添加了额外的方法,但我无法找到文档来列出每个关联的方法是什么以及它们的作用。

class BiologicalMother < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :biological_mother
end

【问题讨论】:

  • 这是“在 belongs_to 和 has_one 之间选择”的官方文档:guides.rubyonrails.org/…,上面写着:"The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association)"

标签: ruby-on-rails associations


【解决方案1】:

在您的情况下,has_manybelongs_to 是正确的方法,不仅在语义上,而且在 rails 的工作方式上也是正确的。外键始终存储在关联的belongs_to 部分中。 一个有效的has_one 场景可能就像有一个Purchase 模型,其中has_one BillingAddress

示例:

class Purchase
   has_one :billing_address
end

class BillingAddress
   belongs_to :purchase #this holds the foreign key - purchase_id
end

关于您的情况,您不能在关联的一侧使用has_many,在关联的另一侧使用has_one,因为belongs_to 部分始终包含外键。

让我知道这是否适合你。

【讨论】:

  • 这是我需要帮助我理解的解释,尤其是我不能在对立的模型上使用 has_one 和 has_many [尽管这似乎不鼓励,但我不知道为什么]。谢谢!
【解决方案2】:

在这一点上,它几乎是纯粹的语义。使用 mongoid,我知道外键存储在带有 belongs_to 的模型上,所以 ActiveRecord 也可能有类似的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多