一个has_many :through协会经常被用来建立一个many-to-many与其他型号的连接。这种关联表明,通过进行第三个模型,可以将声明模型与另一个模型的零个或多个实例匹配。
例如,考虑一种医疗实践,患者会预约去看医生。相关的关联声明如下所示:
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