LEFT OUTER JOIN in Rails 4

前端 未结 12 1742
一整个雨季
一整个雨季 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条回答
  •  旧时难觅i
    2020-11-28 10:25

    Adding to the answer above, to use includes, if you want an OUTER JOIN without referencing the table in the where (like id being nil) or the reference is in a string you can use references. That would look like this:

    Course.includes(:student_enrollments).references(:student_enrollments)
    

    or

    Course.includes(:student_enrollments).references(:student_enrollments).where('student_enrollments.id = ?', nil)
    

    http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-references

提交回复
热议问题