Rails: Has_many through查询取决于through表属性



使用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表有一个名为 Appointment的列

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

Patient.includes(:physicians, :appointments).where('physicians.id = ? AND appointments.appointment_date = ?', <id or ids array>, Date.today)

日期。今天可以改变任何东西,医生是由一个id或一个id数组指定的。

你也可以这样做:

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

在Rails 4及以后的版本中,您需要在查询中添加references(:appointments),以便在where子句中使用约会。

最新更新