我有两张桌子“病人”和“病人资金”
patient:
id status
1 active
2 active
3 inactive
patient_funds:
id required allocated patient_id
1 10 5 1
2 10 10 2
我想从“patient_funds”中选择required
= allocated
的'有效'患者。我想要选择ID为2的“patient_funds”。我怎样才能使用include
。
我试过像
这样的东西Patient.includes(:patient_funds).where(status: "active")
我想在“patient_funds”表中添加另一个条件,正如我解释的那样。 像
这样的东西required LIKE allocated
答案 0 :(得分:2)
使用includes
时,只需将数据与请求一起提取,以防止N + 1查询。
您需要的是join
Patient.joins(:patient_funds).where("patients.status = 'active' AND patient_funds.allocated > ?", 6)
# for example
这将获得patients
和patient_funds
>的所有allocated
6