简体   繁体   中英

rails controller find record with no associations

Student has_many enrollments

Is there a way to see only students that have no enrollments?

Something like:

@students = Student.includes(:enrollments).where(Enrollment.none? })

You could adapt my other answer and say "give me the students whose id s don't appear in the enrolments table" like this:

enrolled  = Enrollment.select(:student_id)
@students = Student.where.not(:id => enrolled)

That will use a subquery inside the database.

An alternative is to do a LEFT JOIN and look for rows that didn't satisfy the join condition:

Student.joins('left join enrollments on students.id = enrollments.student_id')
       .where(:enrollments => { :id => nil })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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