Explore Courses Blog Tutorials Interview Questions
0 votes
in SQL by (20.3k points)

I have 3 models:

class Student < ActiveRecord::Base

  has_many :student_enrollments, dependent: :destroy

  has_many :courses, through: :student_enrollments


class Course < ActiveRecord::Base   

    has_many :student_enrollments, dependent: :destroy

    has_many :students, through: :student_enrollments


class StudentEnrollment < ActiveRecord::Base

    belongs_to :student

    belongs_to :course


What I want is to query for a list of courses in the Courses table, which do not exist in the StudentEnrollments table that are related to a certain student.

I found that perhaps Left Join is the way to go, but it seems that joins() in rails only accept a table as argument. This is the query that I thought would do what I intended:


FROM Courses c LEFT JOIN StudentEnrollment se ON = se.course_id

WHERE IS NULL AND se.student_id = <SOME_STUDENT_ID_VALUE> and = true

Can anyone tell me how I can execute the above query in the Rails 4 way?

Any input is appreciated.

1 Answer

0 votes
by (108k points)
edited by

You can provide a string that is the join-sql. Like:

joins("LEFT JOIN StudentEnrollment se ON = se.course_id")

But, I will suggest you use the rails-standard table naming for better understanding:

joins("LEFT JOIN student_enrollments ON = student_enrollments.course_id")

For more information regarding the same, do refer to the Microsoft SQL Server certification course.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in SQL by Tech4ever (20.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.7k users

Browse Categories