user2320239
user2320239

Reputation: 1038

Getting records where attributes have certain value

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

Answers (2)

Andrey Deineko
Andrey Deineko

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

mahemoff
mahemoff

Reputation: 46389

Another option:

Person.where id: Pet.where(mammal: true).pluck('distinct person_id')

Upvotes: 0

Related Questions