"has_many" 与 "has_many, through" 关系在 rails 中的用法

usage of "has_many" vs "has_many, through" relation in rails

我是 rails 和 web-dev 的新手。

目前我正在学习 "active record Associations" rails 4

我对 "has_many" 与 "has_many, through" 关系的用法感到困惑。

例如,如果我的架构中有医生、预约和患者模型。(如 rails 指南提供的那样)

和rails教程建议我这样做。


class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

但是如果我这样建立关系呢


class Physician < ApplicationRecord
  has_many :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  has_many :patients
end

class Patient < ApplicationRecord
  belongs_to :appointment
end

我认为两者都可以正常工作。

但我想知道有什么区别以及为什么它们会建立 "has_many, through" 关系。

感谢您阅读我的问题。

has_many through 是一种连接两个不相关的、独立的 models/tables 并减少 table 中的 duplicates/redundancy 的方法,其中 has_many 表示更直接的关系.

也许约会和医生的例子不清楚。我给一个不同的。

class Artist
  has_many :paintings
  has_many :purchases
  has_many :buyers, through: :purchases
end

class Painting
  belongs_to :artist
end

class Purchase
  belongs_to :painting
  belongs_to :buyer
end

class Buyer
   has_many :paintings_buyers
   has_many :painting, through: :purchases
end

谈论你的例子。

首先,您没有方便的途径获得医师专利。唯一的办法是:

physician.appoitments.map(&:patient).uniq

这将导致

  1. 表现不佳
  2. 无法使用 sql 过滤实体,只能使用 ruby(再次表现不佳)

还有,你有没有注意到我用了uniq?这是因为当同一位患者被多次指定给同一位医生时,患者的 table 将有很多重复项。