mardi 11 juin 2019

Best way to combine results of two select statements without returning an array?

I'm trying to get one set of unique users from querying two different tables. For example, let's say I want to find the set of unique pet owners. Some owners own dogs, some own cats- I want the number of owners who own a dog or a cat or both.

I know one solution is

dog_owners = Dog.joins(:owner).select(:owner_id).distinct
cat_owners = Cat.joins(:owner).select(:owner_id).distinct
combined_owners = dog_owners + cat_owners
unique_owners = combined_owners.uniq{|x| x.owner_id}
unique_owners.count 

Is there a way to do this where I wouldn't have to use the uniq call, and could use distinct instead? Because the + operator returns an Array, I am not able to use distinct here.

Aucun commentaire:

Enregistrer un commentaire