[英]How do I access attributes of the join model in a has_many :through association
Using the example on rails guides : 使用示例在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
Say Appointment
has the attribute exam_room_id
. 说
Appointment
具有属性exam_room_id
。 I want to use ActiveRecord to obtain a result set that contains a Physician's
Patients
and what exam room the Patient
is in. 我想使用ActiveRecord来获得一个包含
Physician's
Patients
以及Patient
所在的检查室的结果集。
I feel like I should be able to do something like this: 我觉得我应该可以做这样的事情:
Physician.first.patients.each do |patient|
patient.appointment.exam_room_id
end
This does not work because a Physician has_many :appointments
(ie: not a single appointment). 这不起作用,因为
Physician has_many :appointments
(即:不是一个约会)。
Is there an elegant 'rails way' of accessing the attributes of Appointment
together with either side of the has_many :through?
是否有一种优雅的“轨道方法”与
has_many :through?
任意一侧一起访问Appointment
的属性has_many :through?
We can do the following because appointments table is included in the join query implicitly, 我们可以执行以下操作,因为约会表隐式包含在联接查询中,
Physician.first.patients.select("appointments.exam_room_id ")
.each{|patient| patient.exam_root_id}
You're going to have to step through each appointment. 您将必须完成每个约会。
Physician.first.patients.each do |patient|
patient.appointments.each {|appointment| puts appointment.exam_room_id}
end
This would show you every exam room a patient has ever been in (based on their appointments). 这将向您显示患者曾经去过的每个检查室(基于他们的约会)。 I don't think is exactly what you're looking for but wanted to illustrate you need to iterate over each physician or patient appointment to get the room_id.
我不认为这正是您要寻找的东西,但想说明您需要遍历每位医生或患者的约会才能获得room_id。
If you're wanting a result set of current rooms you're going to want to go through the appointments. 如果您想要一组当前房间的结果,则需要进行约会。
Physician.first.appointments.each
. Physician.first.appointments.each
。 Also, how are you distinguishing between current and past appointments? 另外,您如何区分当前约会和过去约会?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.