12

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

约会表有一个名为约会日期的列

我如何从特定医生那里获得在给定日期预约的所有患者?

4

1 回答 1

19
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 子句中使用约会。

于 2013-03-26T16:11:31.003 回答