问题
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 @danceclass.students to get a list of all students enrolled in a danceclass. How do I get the opposite of that? IE. All students not enrolled in this danceclass?
回答1:
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: @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)
来源:https://stackoverflow.com/questions/40854192/find-all-students-not-enrolled-in-a-class-rails