我正试图通过查询两个不同的表来获得一组唯一用户。例如,假设我要查找一组唯一的宠物主人。有些主人拥有狗,有些拥有猫-我想要拥有狗或猫或两者兼有的所有者的数量。
我知道一种解决方法是
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
有没有一种方法可以不必使用uniq
调用,而可以使用distinct
呢?因为+
运算符返回一个数组,所以我不能在这里使用distinct
。
答案 0 :(得分:2)
您能反过来吗?
Owner
.left_outer_joins(:dogs, :cats)
.where("dogs.owner_id IS NOT NULL OR cats.owner_id IS NOT NULL")
.distinct
答案 1 :(得分:0)
我认为加百列希尔的答案更好。我只是将其放在这里,以供可能与OP有相同要求但在条件上具有所需灵活性的任何人使用。
owners = Owner.where(
id: Dog.joins(:owner).select(:owner_id)
).or(
Owner.where(
id: Cat.joins(:owner).select(:owner_id)
)
)