问题描述
曾经试图弄清楚这一点,但我真的很沮丧。
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
我有一个学生模型:
class Student < ActiveRecord::Base
has_many :danceclass_students
has_many :danceclasses, through: :danceclass_students
我有我的加入模型:
class DanceclassStudent < ActiveRecord::Base
belongs_to :student
belongs_to :danceclass
我使用 @ danceclass.students
来获取所有参加 danceclass
的学生的列表。我如何得到相反的结果? IE浏览器所有未参加此舞蹈班
?
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
?
推荐答案
的学生然后应用否定where子句删除不想要的子句。
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 })
加入
是必需的,因为 where
语句正试图根据桥表上的ID减少
The joins
is needed since the where
statement are trying to reduce based on the ID on the bridge table
这将返回所有未参加特定@danceclass的学生,如果它与单个舞蹈课有关。不是您的问题,而是万一其他人遇到这个问题
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)
这篇关于查找所有未上课的学生(铁路)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!