问题
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