使用上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's
Patients
什麼考場的Patient
是在結果集中
我覺得我應該可以做這樣的事情:
Physician.first.patients.each do |patient|
patient.appointment.exam_room_id
end
這確實不工作,因爲Physician has_many :appointments
(即:不是一個約會)。
有一種優雅的「軌道的方式」獲取的Appointment
屬性與的has_many :through?
你需要的結果集返回exam_room_id爲所有的約會? – rb512
我認爲你實際上不得不要求''patient.appointment.first.exam_room_id'' –
rrb:理想情況下,結果集對於「Physician」,「Appointment」和「Patient」的每個組合都有一條記錄 - 就好像查詢是針對預約表所寫的一樣,並且還抓取了醫生和患者的數據。我意識到我可以使用自定義sql甚至ActiveRecord表來解決問題 - 我希望這樣做有一個很好的「rails方式」。 – rswolff