has_and_belongs_to_many并加入表格

时间:2013-09-18 08:01:27

标签: sql ruby-on-rails ruby

我遇到has_and_belongs_to_many关系问题。我有2个模型,Doctors和PatientMeeting。

class Doctor < ActiveRecord::Base
  has_and_belongs_to_many :patient_meetings
end
class PatientMeeting < ActiveRecord::Base
  has_and_belongs_to_many :doctors
end

问题是要显示前50名医生的患者会议(我有一个名为top50的bool变量)。我需要创建一个列出这些会议的查询 医生按降序排列,仅包括今天和明天的日期。我试过这个和变化,但它不起作用:

Doctor.joins(:patient_meetings).where(:top50 => true).where('patient_meetings.meeting_date' => Date.today.strftime("%Y-%m-%d")..Date.tomorrow.strftime("%Y-%m-%d")).order('patient_meetings.meeting_date DESC').limit(50)

我不知道接下来要做什么。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

试试这个:

PatientMeeting.joins(:doctors).where(doctors: {top50: true})

答案 1 :(得分:0)

假设您正在使用mysql。试试这个

 Doctor.joins(:patient_meetings).where("patient_meetings.meeting_date <= CURDATE() + INTERVAL 1 DAY AND patient_meetings.meeting_date >= CURDATE()").order("patient_meetings.meeting_date DESC").limit(50)

答案 2 :(得分:0)

患者与医生的会议显然具有其自身的特定属性,例如其发生的时间,可能是位置,可能是否发生。

在我看来,它应该是一个通过关联的has_many,而不是has_and_belongs_to_many。

http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many