Blogger11 Blogger11 - 1 year ago 78
Ruby Question

Find all students not enrolled in a class (rails)

Been trying to figure this one out for a while and I'm really stumped.

So I have a danceclass model

class Danceclass < ActiveRecord::Base
has_many :danceclass_students
has_many :students, through: :danceclass_students

I Have a student model:

class Student < ActiveRecord::Base
has_many :danceclass_students
has_many :danceclasses, through: :danceclass_students

I have my join model:

class DanceclassStudent < ActiveRecord::Base
belongs_to :student
belongs_to :danceclass

I use
to get a list of all students enrolled in a
. How do I get the opposite of that? IE. All students not enrolled in this

Answer Source

Start with all students then apply a negative where clause to remove the ones you do not want.

Student.joins(:danceclass_students).where.not(danceclass_students: {danceclass_id: })

The joins is needed since the where statement are trying to reduce based on the ID on the bridge table

This will return all students not enrolled in the specific @danceclass if it is related to a single danceclass. Not for your question, but leaving incase anyone else has this problem

Student.where.not(danceclass: @danceclass)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download