Rails Active Record查询只能联接,任何 [英] Rails Active Record Query joins only, any

查看:72
本文介绍了Rails Active Record查询只能联接,任何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Student has_many :enrollments

通过此查询,我看到拥有 true 入学率的学生,还具有两者 true false 报名:

With this query I see those students that have true enrollments, but also those that have both, true and false enrollments:

@students = Student.joins(:enrollments).where(enrollments: { is_active: false })

是否可以添加一些仅属性看到只有名活跃学生的学生?

Is there some "only" attribute that I can add to see students that have only active enrollments?

推荐答案

一种简单的方法是找到学生无效的注册,然后将其明确排除在外。像这样的东西:

One way straightforward would be to find the students that inactive enrolments and then explicitly exclude them. Something like:

have_inactives = Enrollment.where(is_active: false).select(:student_id)
@students      = Student.joins(:enrollments).where.not(id: have_inactives)

joins(:enrollments)会过滤掉没有任何注册的学生条目以及 where.not (...)将排除所有未注册学生(使用子查询,因此所有作业仍将保留在其所属的数据库中)。

The joins(:enrollments) will filter out Student entries that don't have any enrolments and the where.not(...) will exclude all those students that have inactive enrolments (using a subquery so all the work will still be inside the database where it belongs).

顺便说一句,您可能想要修复注册的拼写,双l拼写错误可能最终使您或其他程序员发疯。

BTW, you might want to fix your spelling of "enrolment", the double-l misspelling will probably end up driving you or someone other programmer crazy.

这篇关于Rails Active Record查询只能联接,任何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆