Reputation: 166
This has come up again and again in the project I'm working on so am going to try and get an answer once and for all.
I'm trying to use where, and then collect all of an association. I can't describe the problem well so it may have been answered before (in fact, I'm sure it has) but here is an example.
I have applicant_approvals, which is a join table between a few different relations. It also has its own column, approved
. I'm trying to get all applicant approvals where an applicant has been approved, and then get those applicants. So something like:
@stage.applicant_approvals
.where(approved: true)
.applicants
Now, of course, you can't do that because where
returns an active record association. I don't want to use first because I want all the applicants that have been approved of that stage of the process.
Is there an acknowledged way to do this or do I need to get the association, then run it through an each to get each applicant?
thanks.
Upvotes: 0
Views: 19
Reputation: 102222
You can do this by setting up indirect associations:
class Applicant < ApplicationRecord
has_many :applicant_approvals
has_many :stages, through: :applicant_approvals
end
class ApplicantApproval < ApplicationRecord
belongs_to :applicant
belongs_to :stage
end
class Stage < ApplicationRecord
has_many :applicant_approvals
has_many :applicants, through: :applicant_approvals
end
Then just create pop a where clause onto the association:
@stage.applicants.where(applicant_approvals: { approved: true })
Upvotes: 1