Find all students not enrolled in a class (rails)

﹥>﹥吖頭↗ 提交于 2019-12-12 02:24:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!