tobogranyte
tobogranyte

Reputation: 939

Filtering results of a many to many relationship using data in the join table

I have rails application with two models, StudentProfile and ClassProfile that are associated via a join table (model Enrollment).

In my ClassProfile model, I have:

has_many :enrollments
has_many :student_profiles, through: :enrollments

and in my StudentProfile model, I have:

has_one :enrollment
has_one :class_profile, through: :enrollment

My enrollments table also has a status integer field.

I would like to put a method in the ClassProfile model called "roster" that returns all the student_profiles that have an enrollment status of 1. Right now, I have the following:

def roster
  self.student_profiles
end

Needless to say, all this does is return all students in a class, regardless of enrollment status. I feel like this should be simple, but I've seen no examples of how to add filtering on the join table (enrollments). Is this something I can accomplish in the ClassProfile model, or do I need to do something in Enrollment (or elsewhere)?

Update

From looking through the query reference mentioned by @QMFNP, here's the code that worked:

self.student_profiles.includes(:enrollment).where('enrollments.status = ?', 1)

Needed to change :enrollments to :enrollment because it's a has_one association. And the enrollments field that I'm filtering on is status, so changed enrollments.id to enrollments.status.

Thanks!

Upvotes: 0

Views: 935

Answers (1)

QMFNP
QMFNP

Reputation: 997

This can be accomplished by specifying your query conditions on the association like so:

def roster
  self.student_profiles.includes(:enrollment).where('enrollments.status = ?', 1)
end

This should return your expected results. More information about querying on Active Record associations can be found here:

http://guides.rubyonrails.org/active_record_querying.html

Hope that helps!

Upvotes: 2

Related Questions