Intersection of two relations

sscirrus picture sscirrus · Jun 22, 2011 · Viewed 15.4k times · Source

Say I have two relations that hold records in the same model, such as:

@companies1 = Company.where(...)
@companies2 = Company.where(...)

How can I find the intersection of these two relations, i.e. only those companies that exist within both?

Answer

PeterWong picture PeterWong · Jun 22, 2011

By default connecting those where together creates AND which is what you want.

So many be:

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

@companies = Company.where_1.where_2

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

There are two cases:

# 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

So if you are in case 2, you will need to do like what @apneadiving commented.

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

Of course, doing this sends out two queries and most likely queried more results than you needed.