Rails Active Record Query joins only, any

淺唱寂寞╮ 提交于 2019-12-12 04:21:42

问题


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:

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


回答1:


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


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.



来源:https://stackoverflow.com/questions/41495578/rails-active-record-query-joins-only-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!