我试图从查询两个不同的表中获得一组唯一的用户。例如,假设我想要找到一组独特的宠物主人。有些主人养狗,有些主人养猫--我想知道养狗或养猫或两者都养的主人的人数。
我知道一个解决方案是
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。
发布于 2019-06-12 02:43:20
你能走另一条路吗?
Owner
.left_outer_joins(:dogs, :cats)
.where("dogs.owner_id IS NOT NULL OR cats.owner_id IS NOT NULL")
.distinct发布于 2019-06-12 02:48:35
我认为gabrielhilal的答案更好。我只是把它放在这里,供那些可能有与OP相同的需求,但在条件中具有所需灵活性的人使用。
owners = Owner.where(
id: Dog.joins(:owner).select(:owner_id)
).or(
Owner.where(
id: Cat.joins(:owner).select(:owner_id)
)
)https://stackoverflow.com/questions/56549657
复制相似问题