合并两个 ActiveRecord::Relation 对象 [英] Combine two ActiveRecord::Relation objects

查看:27
本文介绍了合并两个 ActiveRecord::Relation 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个对象:

Suppose I have the following two objects:

first_name_relation = User.where(:first_name => 'Tobias') # ActiveRecord::Relation
last_name_relation  = User.where(:last_name  => 'Fünke') # ActiveRecord::Relation

是否有可能将这两种关系结合起来产生一个包含这两个条件的 ActiveRecord::Relation 对象?

is it possible to combine the two relations to produce one ActiveRecord::Relation object containing both conditions?

注意:我知道我可以链接 wheres 来获得这种行为,我真正感兴趣的是我有两个单独的 ActiveRecord::Relation 对象的情况.

Note: I'm aware that I can chain the wheres to get this behavior, what I'm really interested in is the case where I have two separate ActiveRecord::Relation objects.

推荐答案

如果您想使用 AND(交集)进行组合,请使用 merge:

If you want to combine using AND (intersection), use merge:

first_name_relation.merge(last_name_relation)

如果您想使用 OR(联合)进行组合,请使用 or:

If you want to combine using OR (union), use or:

first_name_relation.or(last_name_relation)

<小时>

仅在 ActiveRecord 5+ 中;对于 4.2 安装 where-or 反向移植.


Only in ActiveRecord 5+; for 4.2 install the where-or backport.

这篇关于合并两个 ActiveRecord::Relation 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆