2017-06-29 142 views
2

我有模型,医师,has_many患者。尝试写一个查询,只会导致医生拥有所有治愈的患者。因此,每位医师患者必须具有“is_cured:true”的属性(或者对于所有内科医生患者至少不是零)。Ruby has_many与Postgres数据库相关的模型查询(Rails 5)

有这到目前为止,但医生们表示只是有一个治愈病人,不是所有的时候了:

@physicians = Physician.includes(:patients) .where.not(patients: { id: nil }) .where(patients: { is_cured: true })

型号:

class Physician < ApplicationRecord 
    has_many :patients 
    has_many :recommendations, through: :patients 
end 

class Patient < ApplicationRecord 
    belongs_to :physician 
    belongs_to :recommendation 
end 

class Recommendation < ApplicationRecord 
    has_many :patients 
    has_many :physicians, through: :patients 
end 

感谢您能给任何帮助!

回答

0
# Fetches physicians who have at-least one uncured patient 
phys_with_uncured_patients = Physician.joins(:patients).where(patients: { is_cured: false }) 

#Fetches physicians who have at-least one patient and all are cured. 
Physician.joins(:patients).where.not(id: phys_with_uncured_patients) 
0
physician_ids = Patient.where(is_cured: false).pluck(:physician_id) 

Physician.joins(:patients).where.not(id: physician_ids) 
+0

问题也有望筛选出谁拥有零名病人的医生,你的第二个查询不过滤。 – Ucpuzz

+0

在这种情况下'加入'将做到这一点。好点子。 –