Rails has_and_belongs_to_many关联:如何检索没有特定关联记录的记录

时间:2018-01-10 18:24:49

标签: sql ruby-on-rails postgresql ruby-on-rails-5

假设有学生和教师模特:

class Student < ApplicationRecord
  has_and_belongs_to_many :teachers
end

class Teacher < ApplicationRecord
  has_and_belongs_to_many :students
end

,数据库架构看起来像这样

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

我在DB上播种了以下内容:

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]

现在我想让所有没有students[0]的老师。但是当我跑步时

Teacher.includes(:students).where.not(students: {id: students[0].id})

它返回teacher_1teacher_2。有没有办法让所有没有指定学生的老师? (本例中为teacher_2&amp; teacher_3

我也试过

Teacher.includes(:students).where("students.id != ? OR students.id IS NULL", students[0].id).references(:students)

但它会让所有三位老师回归。

我努力找到任何可以帮助我在互联网上的东西但到目前为止没有运气:(

更新1:

正如@ruby_newbie在下面评论过的那样,查询结果包含teacher_1因为teacher_1还有一个其他学生(student[1]),但我想让所有没有特定学生的老师说student[0]无论他们是否有其他学生。

0 个答案:

没有答案