2011-10-25 27 views
0

使用上rails guides的例子:如何访问的连接模型的属性在的has_many:通过关联

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'sPatients什么考场的Patient是在结果集中

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

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

这确实不工作,因为Physician has_many :appointments(即:不是一个约会)。

有一种优雅的“轨道的方式”获取的Appointment属性与的has_many :through?

+0

你需要的结果集返回exam_room_id为所有的约会? – rb512

+0

我认为你实际上不得不要求''patient.appointment.first.exam_room_id'' –

+0

rrb:理想情况下,结果集对于“Physician”,“Appointment”和“Patient”的每个组合都有一条记录 - 就好像查询是针对预约表所写的一样,并且还抓取了医生和患者的数据。我意识到我可以使用自定义sql甚至ActiveRecord表来解决问题 - 我希望这样做有一个很好的“rails方式”。 – rswolff

回答

0

两侧你将不得不步每个约会在一起的。

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

这会告诉你病人曾经住过的每个考场(根据他们的约会)。我不认为这正是你正在寻找的,但是想要说明你需要重复每个医生或患者的预约以获得room_id。

如果你想要结果集的当前房间,你会想要通过约会。 Physician.first.appointments.each。另外,你如何区分当前和过去的约会?

1

我们可以做以下,因为预约表包含在连接查询含蓄,

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