LEFT OUTER JOIN in Rails 4

前端 未结 12 1731
一整个雨季
一整个雨季 2020-11-28 09:44

I have 3 models:

class Student < ActiveRecord::Base
  has_many :student_enrollments, dependent: :destroy
  has_many :courses, through: :student_enrollment         


        
12条回答
  •  情歌与酒
    2020-11-28 10:03

    Combining includes and where results in ActiveRecord performing a LEFT OUTER JOIN behind the scenes (without the where this would generate the normal set of two queries).

    So you could do something like:

    Course.includes(:student_enrollments).where(student_enrollments: { course_id: nil })
    

    Docs here: http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations

提交回复
热议问题