本文介绍了Rails:Has_many through 查询取决于 through 表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过查询使用 has_many 时遇到一些问题.

Having some problems with a has_many through query.

使用此处的示例: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

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

How would I get all the Patients from a Specific Physician that have an appointment on a given date?

推荐答案

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

Date.today 可以用任何东西改变,医生是由一个 id 或一组 id 指定的.

Where Date.today could be changed with anything and the pysician is specified by an id or an array of ids.

你也可以这样做:

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

在 Rails 4 及更高版本中,您需要将 references(:appointments) 添加到查询中,以便在 where 子句中使用约会.

In Rails 4 and forward, you need to add references(:appointments) to the query in order to use appointments in the where clause.

这篇关于Rails:Has_many through 查询取决于 through 表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:54