Reputation: 155
I have two nested objects: RecruitmentUser that has_many RecruitmentUserStatusLog. RecruitmentUserStatusLog has an attibute called status. I want to select RecruitmentUsers that have RecruitmentUserStatusLog with status='processed' AND RecruitmentUserStatusLog with status='answered'. It can't be just one of them.. I tried some queries using ActiveRecord but I don't know if it is the most efficient way.. I tried this:
RecruitmentUserStatusLog.where(status: ['processed', 'answered']).pluck(:recruitment_user_id).group_by {|id| id}.values.select{|duplicate_id| duplicate_id.size > 1}
The select part is just for getting the occurances of id that are repeated (recruitment_user_id that has status 'processed' AND recruitment_user_id that has status 'answered').
But I think it's' much work and maybe there is a more elegant way to do this query.. I've searched but didn't find it.. Can anybody help me?
Upvotes: 0
Views: 120
Reputation: 3521
try this
user_ids = RecruitmentUserStatusLog.where(status: ['processed', 'answered'])
.group(:recruitment_user_id)
.having("count(recruitment_user_id) > 1")
.count
.keys
users = RecruitmentUser.find(user_ids)
Upvotes: 1