ruby-on-rails – 两个关系的交集

我有两个关系在同一个模型中保存记录,如:
@companies1 = Company.where(...)
@companies2 = Company.where(...)

我如何找到这两个关系的交集,即只有那些存在于两者之间的公司?

解决方法

认情况下连接那些在一起创建的,哪个是你想要的.

这么多是:

class Company < ActiveRecord::Base
  def self.where_1
    where(...)
  end
  def self.where_2
    where(...)
  end
end

@companies = Company.where_1.where_2

====== UPDATED ======

有两种情况:

# 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,3]) & Company.where(:id => [1,4,5])

# the result would be the same as
Company.where(:id => [1,5])
# because it is &-ing the :id key,instead of the content inside :id key

所以如果你是2,你需要像@apneadiving这样评论.

Company.where(...).all & Company.where(...).all

当然,这样做会发出两个查询,最有可能查询比您需要的更多的结果.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...