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

前端之家收集整理的这篇文章主要介绍了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

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

原文链接:https://www.f2er.com/ruby/266935.html

猜你在找的Ruby相关文章