说我有两个关系在同一个模型中保存记录,如:
@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