Question: Rails Active Record Query joins only, any

Question

Rails Active Record Query joins only, any

Answers 1
Added at 2017-01-05 23:01
Tags
Question
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?

Answers to

Rails Active Record Query joins only, any

nr: #1 dodano: 2017-01-06 00:01

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.

Source Show
◀ Wstecz