繁体   English   中英

多个包含ActiveRecord Rails的where子句

[英]Multiple where clause with include ActiveRecord Rails

我有两个表“病人”和“病人资金”

patient:
id   status
1    active
2    active
3    inactive

patient_funds:
id    required    allocated   patient_id
1     10             5            1
2     10             10           2

我要选择具有“主动”患者required = allocated从“patient_funds”。 我想选择ID为2的“ Patient_funds”。 如何使用include做到这一点。

我尝试了类似的东西

Patient.includes(:patient_funds).where(status: "active")

正如我所解释的,我想在“ Patient_funds”表上添加另一个条件。 就像是

required LIKE allocated

使用includes它只会将数据与请求一起拉出,以防止进行N + 1查询。

您需要的是加入

Patient.joins(:patient_funds).where("patients.status = 'active' AND patient_funds.allocated > ?", 6)
# for example

这将使所有拥有patient_fundsallocated > 6的patients

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM