在不返回数组的情况下组合两个 select 语句的结果的最佳方法



我正在尝试从查询两个不同的表中获取一组唯一用户。例如,假设我想找到一组独特的宠物主人。有些主人养狗,有些养猫——我想要拥有狗或猫或两者兼而有之的主人的数量。

我知道一个解决方案是

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

你能反过来吗?

Owner
   .left_outer_joins(:dogs, :cats)
   .where("dogs.owner_id IS NOT NULL OR cats.owner_id IS NOT NULL")
   .distinct

我认为加布里埃尔希拉尔的答案更好。我只是把它放在这里,供任何可能与 OP 有相同要求但在条件上具有所需灵活性的人使用。

owners = Owner.where(
  id: Dog.joins(:owner).select(:owner_id)
).or(
  Owner.where(
    id: Cat.joins(:owner).select(:owner_id)
  )
)

最新更新