2011-10-25 29 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} 
相關問題