2017-06-29 18 views
2

私は、has_many Patientsというモデル、医師を抱えています。試してみると、治癒したすべての患者さんがいる医師にしか見えない質問が書かれています。したがって、医師の各患者は、属性が "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

質問はまた、あなたの2番目のクエリは、それらをフィルタリングしない、ゼロの患者を持つ医師をフィルタリングする予定。 – Ucpuzz

+0

その場合、 'join 'がそのトリックを行います。いい視点ね。 –

関連する問題