我正在尝试使用 Rails ORM 编写查询。假设有两个模型。
class College
has_many :students
class Student
belongs_to :college
Student
表有一列名为 result
,可以是 pass
或 fail
现在,我只想获取所有学生都有 passed
的大学列表。
我尝试了以下方法
College.join(:students).group('colleges.id, students.results').select('colleges.id, count(students) as students_count').where(students: {result: 'pass'}).having('count(*) = students_count')
但我收到此错误:
Caused by PG::UndefinedColumn: ERROR: column "students_count" does not exist
最好的方法是使用否定子查询:
College.where.not(id: Student.select(:college_id).where(result: "fail"))