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

标签 ruby-on-rails ruby-on-rails-3 activerecord relation

假设我有两个关系在同一模型中保存记录,例如:

@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/

相关文章:

sql - 显示消息数组中的最后一条消息

ruby-on-rails - ruby 将值添加到以逗号分隔的字符串,除了第一个元素

ruby-on-rails - 为用户搜索添加邻近过滤器

ruby-on-rails - Rails 3,具有 lambda 条件的 has_one/has_many

sql - rails : Group and sum while adding last values (Fibonacci)

ruby-on-rails - 设计不使用自定义邮件 View

ruby-on-rails - Rails Devise Invitable 发送邀请后重定向

ruby-on-rails-3 - 轨道 3 : Modify error message prefix for form validation

ruby-on-rails - 没有这样的列 - 当列存在时

ruby-on-rails - ActiveRecord 在类加载时加载关系表作为枚举实例