Let's say have Student and a Teacher models:
class Student < ApplicationRecord
has_and_belongs_to_many :teachers
end
class Teacher < ApplicationRecord
has_and_belongs_to_many :students
end
and the DB schema looks something like this
create_table "students", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "students_teachers", id: false, force: :cascade do |t|
t.bigint "student_id", null: false
t.bigint "teacher_id", null: false
t.index ["student_id", "teacher_id"], name: "index_students_teachers_on_student_id_and_teacher_id"
t.index ["teacher_id", "student_id"], name: "index_students_teachers_on_teacher_id_and_student_id"
end
create_table "teachers", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
and I have seeded the DB with following:
students = Student.create([{}, {}, {}, {}])
teacher_1 = Teacher.create
teacher_2 = Teacher.create
teacher_3 = Teacher.create
teacher_1.students << [students[0], students[1]]
teacher_2.students << students[1]
Now I want to get all teachers which don't have students[0]
. But when I run
Teacher.includes(:students).where.not(students: {id: students[0].id})
it returns teacher_1
and teacher_2
. Is there any way to get all teachers which don't have the specified student? (teacher_2
& teacher_3
in this case).
I also tried
Teacher.includes(:students).where("students.id != ? OR students.id IS NULL", students[0].id).references(:students)
but it returns all three teachers.
I tried hard finding anything that can help me on the internet but no luck so far :(
Update 1:
As @ruby_newbie commented below, the query results includes teacher_1
because teacher_1
have one other student (student[1]
) but I want to get all teachers which do not have a particular student say student[0]
no matter if they have other students.