gpt4 book ai didi

ruby-on-rails - ActiveRecord .where of .join/has_one :through

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:33 26 4
gpt4 key购买 nike

我有三个模型 - PatientLocationArea

每个患者都属于一个位置,而位置又属于区域。区域有一个名为 inpatient 的 bool 值。

我需要选择属于某个位置的患者,而该位置又属于住院值设置为 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

最佳答案

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

@inpatient = Patient.joins(:location).joins(:area).where(locations: {areas: {inpatient: true}}) 

关于ruby-on-rails - ActiveRecord .where of .join/has_one :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com