代码之家  ›  专栏  ›  技术社区  ›  Oliver Trampleasure

ActiveRecord.where of.join/has_one:通过

  •  2
  • Oliver Trampleasure  · 技术社区  · 7 年前

    我有三种型号- Patient Location 和 Area .

    每个患者都属于一个位置,而位置属于多个区域。 区域有一个布尔值,称为 inpatient .

    我需要选择属于某个位置的患者,而该位置又属于“住院患者”值设置为true的区域。

    我尝试了以下方法,但均无效:

    @inpatient = Area.joins(:locations).joins(:patients).where(inpatient: true).count
    @inpatient = Patient.joins(:location).join(:area).where(area: {inpatient: true}) 
    @inpatient = Patient.joins(:area).where(area: {inpatient: true}).all 
    @inpatient = Patient.joins(:location).joins(:area).where(area: {inpatient: true}).count
    

    谢谢你的帮助!我想这很简单,我犯了一些基本的错误。。。我已经看了其他问题,这些问题都很相似,但无法将答案重新组合成任何可行的问题。


    模型

    class Patient < ApplicationRecord
    
      belongs_to :location, optional: true
      has_one :area, through: :location
    
    end
    

    -

    class Location < ApplicationRecord
    
      has_many :patients
      belongs_to :area, optional: false
    
    end
    

    class Area < ApplicationRecord
    
      has_many :locations
      has_many :patients, through: :locations
    
    end
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Noah    7 年前

    你很接近。必须在where语句中使用表名,而不是关系名。此外,还必须在locations参数中使用区域。试试这个:

    @inpatient = Patient.joins(:location).joins(:area).where(locations: {areas: {inpatient: true}}) 
    
        2
  •  0
  •   Vasilisa    7 年前

    您可以使用您的关联,它应该生成相同的SQL查询,但它更简单、更可读

    @inpatient = Area.where(inpatient: true).patients