简体   繁体   English

多个包含ActiveRecord Rails的where子句

[英]Multiple where clause with include ActiveRecord Rails

I have two tables "patients" and "patient_funds" 我有两个表“病人”和“病人资金”

patient:
id   status
1    active
2    active
3    inactive

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

I want to select 'active' patients having required = allocated from "patient_funds". 我要选择具有“主动”患者required = allocated从“patient_funds”。 i,e I want "patient_funds" with id 2 to be selected. 我想选择ID为2的“ Patient_funds”。 How can I do it using include . 如何使用include做到这一点。

I tried something like 我尝试了类似的东西

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

I want to add another condition on "patient_funds" table as I explained. 正如我所解释的,我想在“ Patient_funds”表上添加另一个条件。 Something like 就像是

required LIKE allocated

When you use includes it just pulls data alongside your request to prevent N+1 query. 使用includes它只会将数据与请求一起拉出,以防止进行N + 1查询。

What you need is join 您需要的是加入

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

This will get all patients that have patient_funds and allocated > 6 这将使所有拥有patient_fundsallocated > 6的patients

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

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