包含ActiveRecord Rails的多个where子句

时间:2015-07-02 12:11:45

标签: ruby-on-rails eager-loading

我有两张桌子“病人”和“病人资金”

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

1 个答案:

答案 0 :(得分:2)

使用includes时,只需将数据与请求一起提取,以防止N + 1查询。

您需要的是join

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

这将获得patientspatient_funds>的所有allocated 6