2014-01-26 13 views
0

假設我們有從Rails的導向著名的場景:Rails的:最好的方式得到了「通過」中的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.where(physician: my_physician, patient: my_patient,但感覺很髒。是不是有一種方法可以通過返回單個記錄?

回答

0

你可以使用

my_physician.appointments.where(patient: my_patient) 
+0

其實我明白了:我想更換其中由find_by是乾淨的解決方案 – soBinary

+0

但是'find_by_ *'只會返回一個紀錄,因爲它增加了'LIMIT 1'到SQL查詢!所以如果一位醫生和一位患者有多個預約,你只會得到第一個預約。在以前的Rails版本中,有'find_all_by_ *',但現在已被棄用,並告訴您使用'where'代替。 –

+0

[來自Rails指南](http://guides.rubyonrails.org/active_record_querying.html#find-by):「Model.find_by查找符合某些條件的第一條記錄。」 –