繁体   English   中英

Ruby on Rails的归属关系与has_one关联-要求澄清

[英]Ruby on Rails belongs_to vs. has_one associations - clarification requested

在以下实例中,对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

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

在您的情况下,不仅在语义上而且在Rails的工作方式上, has_many belongs_to是正确的方法。 外键始终存储在关联的belongs_to部分中。 有效的has_one场景可能类似于具有has_one BillingAddressPurchase模型。

例:

class Purchase
   has_one :billing_address
end

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

对于您的情况,您不能在关联的一侧使用has_manyhas_many在另一侧使用has_one ,因为belongs_to部分始终持有外键。

让我知道这是否适合您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM