Reputation: 1038
I have a project with a model Person, a person has many Pets, and a Pet and a Boolean attribute Mammal, Id like to be able to retrieve all people whose have at least one pet who is a mammal, but I'm not sure how to do this, I've tried:
Person.includes(:pets).where(pets: {mammal: true})
but it doesn't seem to work. What is the best way for me to do this?
Upvotes: 1
Views: 39
Reputation: 52357
In where
clause there should be the actual name of the database table - in your case its pets
:
Person.joins(:pets).where(pets: { mammal: true }).group('persons.id')
Upvotes: 1
Reputation: 46389
Another option:
Person.where id: Pet.where(mammal: true).pluck('distinct person_id')
Upvotes: 0