问题描述
我有 3 个模型:
class Student < ActiveRecord::Base
has_many :student_enrollments, dependent: :destroy
has_many :courses, through: :student_enrollments
end
class Course < ActiveRecord::Base
has_many :student_enrollments, dependent: :destroy
has_many :students, through: :student_enrollments
end
class StudentEnrollment < ActiveRecord::Base
belongs_to :student
belongs_to :course
end
我希望在 Courses 表中查询与某个学生相关联的 StudentEnrollments 表中不存在的课程列表.
I wish to query for a list of courses in the Courses table, that do not exist in the StudentEnrollments table that are associated with a certain student.
我发现也许 Left Join 是可行的方法,但似乎 rails 中的 joins() 只接受一个表作为参数.我认为可以执行我想要的 SQL 查询是:
I found that perhaps Left Join is the way to go, but it seems that joins() in rails only accept a table as argument.The SQL query that I think would do what I want is:
SELECT *
FROM Courses c LEFT JOIN StudentEnrollment se ON c.id = se.course_id
WHERE se.id IS NULL AND se.student_id = <SOME_STUDENT_ID_VALUE> and c.active = true
我如何以 Rails 4 的方式执行这个查询?
How do I execute this query the Rails 4 way?
感谢任何输入.
推荐答案
您也可以传递一个字符串作为 join-sql.例如 joins("LEFT JOIN StudentEnrollment se ON c.id = se.course_id")
You can pass a string that is the join-sql too. eg joins("LEFT JOIN StudentEnrollment se ON c.id = se.course_id")
虽然为了清楚起见,我会使用 rails 标准的表命名:
Though I'd use rails-standard table naming for clarity:
joins("LEFT JOIN student_enrollments ON courses.id = student_enrollments.course_id")
这篇关于Rails 4 中的左外连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!