在has_many直通查询中遇到一些问题。
使用此处的示例:http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
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
的列如何让特定医生的所有患者在指定日期预约?
答案 0 :(得分:16)
Patient.includes(:physicians, :appointments).where('physicians.id = ? AND appointments.appointment_date = ?', <id or ids array>, Date.today)
Date.today可以用任何东西改变,而pysician由id或id数组指定。
你也可以这样做:
physician = Physician.find(id)
patients = physician.patients.includes(:appointments).where('appointments.appointment_date = ?', some_date)
编辑:
在Rails 4和转发中,您需要将references(:appointments)
添加到查询中,以便在where子句中使用约会。