Intersection of two relations

前端 未结 5 2115
情歌与酒
情歌与酒 2020-12-16 17:06

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

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

Ho

5条回答
  •  余生分开走
    2020-12-16 17:37

    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.

提交回复
热议问题