假设我有两个关系在同一模型中保存记录,例如:
@companies1 = Company.where(...)
@companies2 = Company.where(...)
如何找到这两种关系的交集,即仅存在于两者中的那些公司?
最佳答案
默认情况下,将这些 where
连接在一起会创建您想要的 AND。
很多是:
class Company < ActiveRecord::Base
def self.where_1
where(...)
end
def self.where_2
where(...)
end
end
@companies = Company.where_1.where_2
======已更新======
有两种情况:
# case 1: the fields selecting are different
Company.where(:id => [1, 2, 3, 4]) & Company.where(:other_field => true)
# a-rel supports &, |, +, -, but please notice case 2
# case 2
Company.where(:id => [1, 2, 3]) & Company.where(:id => [1, 2, 4, 5])
# the result would be the same as
Company.where(:id => [1, 2, 4, 5])
# because it is &-ing the :id key, instead of the content inside :id key
因此,如果您属于情况 2,则需要按照@apneadiving 的评论进行操作。
Company.where(...).all & Company.where(...).all
当然,这样做会发出两个查询,并且很可能查询到比您需要的更多的结果。
关于ruby-on-rails - 两个关系的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435389/