Scoping a Rails Model by an Attribute of Its Child
Today I ran into an interesting problem. I needed to scope a Rails model by checking whether it had a child with a certain attribute. The solution was simple but a little hard to find online, so I thought I’d share.
I started out with two models: Applicant
and Application
. Every applicant has_one
application, and every application has a status. I want to create an :active
scope for the Applicant
class, in order to list only applicants whose application status is "in review"
. Here are the models.
Creating the Scope
It turned out creating the scope was simple. All I had to do was add one line to the Applicant
class:
That’s it! The joins
method creates a JOIN
SQL statement on the applications
table, returning the application whose applicant_id
matches the ID of the applicant in question. That enables us to access the attributes of the applicant’s application to check if it is "in review"
and return the applicant as part of the collection if so.
Do note that the joins
method requires :application
to be singular, while in the argument to the where
method, it should be plural.