Search code examples
ruby-on-railsruby-on-rails-4activerecordrails-activerecord

Find all students not enrolled in specific course


I am trying to solve this one but no success till now.

I have 3 models.

Course Model:

class Course < ActiveRecord::Base
    has_many :student_courses
    has_many :students, :through => :student_courses
end

Student Model:

class Student < ActiveRecord::Base
    has_many :student_courses
    has_many :courses, :through => :student_courses
end

Joining Model:

class StudentCourse < ActiveRecord::Base
    belongs_to :student
    belongs_to :course
end

I am trying to send to the view only the students that aren't enrolled in the currently selected course so the opposite of @course.students

I have found this Find all students not enrolled in a class (rails) Which looks very promising except that it doesn't include new students that aren't enrolled in any course, in that question using left_outer_joins is a proposition which doesn't appear to work for them but doesn't help me as I can't update rails over 4.2.5 and it requires rails 5.

Anyone can think of an other solution?


Solution

  • Student.where.not(id: @course.students).all