2

我的Program班级 has_manyPatientsPatient班级有一个像salary

我传递给 JBuilder 的 jsonrespond_to :json , respond_with(@org)是这样的:

@org = Org.includes(programs: [{hospitals: :nurses}, :patients]).find(params[:id])

现在,如果我的数据库有 200 个满足org_id = params[:id]条件的程序,它将全部返回。但这不是我想要的。我想告诉它返回“5”个程序和那些“5”个程序,他们的“患者”表的“薪水”字段是最高的。

如何在活动记录查询中实现此限制?

4

1 回答 1

1

就像是

Program.includes([{hospitals: :nurses}, :patients]).where("organization_id = ?", params[:id]).order("patients.salary desc").limit(5)

或者你可以这样做:

@program_ids = Program.select("id").includes([{hospitals: :nurses}, :patients]).where("organization_id = ?", params[:id]).order("patients.salary desc").limit(5)
@org = Org.includes(programs: [{hospitals: :nurses}, :patients]).where("programs.id = ?", program_ids.collect(&:id)).find(params[:id])

您还可以通过检查以下问题,一步重构子查询(仍然是 2 个查询):

活动记录中的子查询

我不确定您是否可以在一个查询中获得该信息

于 2013-03-03T01:47:48.283 回答