Blogger11 - 4 months ago 37

Ruby Question

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`

`danceclass`

`danceclass`

Answer

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)
```