我有模型,内科医生,has_many病人。尝试编写一个查询,使其只得到所有已治愈患者的医生。因此,对于内科医生来说,每个患者必须具有"is_cured: true“属性(或者至少对于所有内科医生患者来说不是空的)。
到目前为止已经有了这个,但医生们只有一个治愈的病人,而不是所有的:
@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感谢您所能提供的任何帮助!
发布于 2017-06-30 04:48:03
# 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)发布于 2017-06-30 05:31:31
physician_ids = Patient.where(is_cured: false).pluck(:physician_id)
Physician.joins(:patients).where.not(id: physician_ids)https://stackoverflow.com/questions/44834073
复制相似问题