I have a table courses
and a table volunteer_rosters
. courses
contains a list of all courses and volunteer_rosters
contains a list of volunteers teaching/assisting on the course.
I want to write a query that returns a list of all courses that do not have any volunteers assigned to it. This is what is happening:
courses
-------
id
1
3
4
5
6
volunteer_courses
-----------------
id 1 course_id 1
id 2 course_id 1
id 3 course_id 1
id 5 course_id 3
id 6 course_id 3
All of the below queries are returning
course_id 3
course_id 4
course_id 5
Why is course_id 1 (correctly) being left out, but course_id 3 is not???
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id where student_rosters.course_id is null")
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id").where(student_rosters: {id: nil})
Course.includes(:student_rosters).references(:student_rosters).where(student_rosters: {id: nil})
Course.includes(:student_rosters).references(:student_rosters).where('student_rosters.id = ?', nil)
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id").where(student_rosters: {id: nil})
Same exact question, but none of the solutions are working for me: