【问题标题】:Ruby has_many associated models query with Postgres database (Rails 5)Ruby has_many 使用 Postgres 数据库查询关联模型(Rails 5)
【发布时间】:2017-06-29 20:06:26
【问题描述】:

我有模型,医生,有_many 患者。尝试编写一个查询,该查询只导致所有治愈患者的医生。因此,对于一个 Physician 的每个 Patient 都必须具有属性“is_cured: true”(或者至少对于所有 Physicians 患者来说不是 nil)。

目前为止有这个,但是当只有一名治愈患者时,医生会出现,而不是全部:

@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

感谢您提供的任何帮助!

【问题讨论】:

    标签: ruby-on-rails ruby postgresql


    【解决方案1】:
    # 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)
    

    【讨论】:

      【解决方案2】:
      physician_ids = Patient.where(is_cured: false).pluck(:physician_id)
      
      Physician.joins(:patients).where.not(id: physician_ids)
      

      【讨论】:

      • 该问题还希望过滤掉患者为零的医生,您的第二个查询不会过滤掉他们。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多