简体   繁体   English

Rails Active Record查询只能联接,任何

[英]Rails Active Record Query joins only, any

Student has_many :enrollments

With this query I see those students that have true enrollments, but also those that have both , true and false enrollments: 与此查询我看到那些让学生true入学率,还有那些同时具有, truefalse招生:

@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)

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). joins(:enrollments)将过滤掉没有任何注册的Student条目,而where.not(...)将排除所有没有注册的学生(使用子查询,因此所有工作仍将在所属的数据库)。


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. 顺便说一句,您可能想要修复“注册”的拼写,双l错误拼写可能最终会使您或其他程序员疯狂。

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

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