2013-03-26 14 views
7

has_many throughクエリにいくつか問題があります。 http://guides.rubyonrails.org/association_basics.html#the-has_many-through-associationRails has_many throughクエリは、throughテーブル属性によって異なります。

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_date

という名前の列があります。ここでは例を使用して

答えて

13

ここで、Date.todayは何でも変更でき、ピシシアンはIDまたはIDの配列によって指定されます。あなたも行うことができ

physician = Physician.find(id) 
patients = physician.patients.includes(:appointments).where('appointments.appointment_date = ?', some_date) 

編集:Railsの4で

や転送を、あなたは、where句で予定を使用するために、クエリにreferences(:appointments)を追加する必要があります。

+1

素晴らしい!ありがとうございました。 – Ghar

+1

これはレール4で私のために働かなかった、私はかなりの時間を探索し、[この解決策]を見つけた(http://stackoverflow.com/questions/18799934/has-many-through-how-do-you -access-join-table-attributes)4: –

+1

ええ、レール4では、includesからテーブル名を参照するために 'references'を使う必要があります。 – spullen

関連する問題