【问题标题】:rails has_many vs has_many through?rails has_many vs has_many通过?
【发布时间】:2020-02-22 18:15:06
【问题描述】:

我已经了解了关系标识符 has_manyhas_many through。我似乎无法理解的是它们之间的区别。例如,如果我有 3 个模型,医生、约会和患者

 class Doctor< ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :doctor
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :doctors, through: :appointments
end

我不能只说 Doctor has_many :patients 和 Patient has_many :doctors 并且他们是相关的吗?通过预约来做这件事的目的是什么?

谢谢

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你是对的。如果你说一个医生has_many :patients 和一个病人has_many :doctors,那么他们将是相关的。

    但是,我认为本教程的目的是多对多关联。

    如果医生模型和患者模型通过has_many 关联,则医生独占拥有一个患者,而一个患者拥有一个医生。但通常情况并非如此。一个医生可以有很多病人,这些病人不一定是医生的专属;他们可能有其他医生。

    这时多对多关联就出现了。在多对多关联中,一个对象可以有许多属于它的对象,但不是唯一的.就像医生模型和病人模型之间的关联一样。

    有两种方法可以创建多对多关联:

    1. has_and_belongs_to_many
    2. has_many #something through: #joining table

    在您的情况下,您使用的是第二种方式,连接表assocation

    查看这个Railscast 对这两个的详细解释。另外,这个this official Rails documentation on associations 会很有帮助。

    【讨论】:

      【解决方案2】:

      使用“通过”表的唯一原因是当您想使用中间表中包含的一些相关数据时,在本例中是与医生和患者相关的预约数据。

      另外,has_many 需要一个相关的belongs_to,反之亦然,因此您必须在两个模型中使用has_and_belongs_to_many 来表示多对多关系,并创建适当的连接表来配合它.

      否则,是的,您可以简单地在各自的文件中使用 has_and_belongs_to_many :patientshas_and_belongs_to_many :doctors

      请特别注意Rails Guide 中的第 2.8 节。可能需要通读几遍,但一旦你明白了,我保证,它会很有意义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 1970-01-01
        • 2011-11-19
        • 1970-01-01
        • 2017-06-02
        相关资源
        最近更新 更多