繁体   English   中英

如何在has_many:through关联中访问联接模型的属性

[英]How do I access attributes of the join model in a has_many :through association

使用示例在rails guides上

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

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

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

Appointment具有属性exam_room_id 我想使用ActiveRecord来获得一个包含Physician's Patients以及Patient所在的检查室的结果集。

我觉得我应该可以做这样的事情:

Physician.first.patients.each do |patient|
  patient.appointment.exam_room_id    
end

这不起作用,因为Physician has_many :appointments (即:不是一个约会)。

是否有一种优雅的“轨道方法”与has_many :through?任意一侧一起访问Appointment的属性has_many :through?

我们可以执行以下操作,因为约会表隐式包含在联接查询中,

Physician.first.patients.select("appointments.exam_room_id ")
   .each{|patient| patient.exam_root_id}

您将必须完成每个约会。

Physician.first.patients.each do |patient|
  patient.appointments.each {|appointment| puts appointment.exam_room_id}
end

这将向您显示患者曾经去过的每个检查室(基于他们的约会)。 我不认为这正是您要寻找的东西,但想说明您需要遍历每位医生或患者的约会才能获得room_id。

如果您想要一组当前房间的结果,则需要进行约会。 Physician.first.appointments.each 另外,您如何区分当前约会和过去约会?

暂无
暂无

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

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