ActiveRecord Arel OR 条件 [英] ActiveRecord Arel OR condition

查看:23
本文介绍了ActiveRecord Arel OR 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用逻辑 OR 而不是 AND 来组合 2 个不同的条件?

How can you combine 2 different conditions using logical OR instead of AND?

注意: 2 个条件是作为 rails 作用域生成的,不能轻易地直接更改为 where("x or y") 之类的内容.

NOTE: 2 conditions are generated as rails scopes and can't be easily changed into something like where("x or y") directly.

简单例子:

admins = User.where(:kind => :admin)
authors = User.where(:kind => :author)

很容易应用 AND 条件(对于这种特殊情况是没有意义的):

It's easy to apply AND condition (which for this particular case is meaningless):

(admins.merge authors).to_sql
#=> select ... from ... where kind = 'admin' AND kind = 'author'

但是您如何生成以下具有 2 个不同 Arel 关系可用的查询?

But how can you produce the following query having 2 different Arel relations already available?

#=> select ... from ... where kind = 'admin' OR kind = 'author'

似乎(根据 Arel 自述文件):

尚不支持 OR 运算符

The OR operator is not yet supported

但我希望它在这里不适用,并希望写出类似的东西:

But I hope it doesn't apply here and expect to write something like:

(admins.or authors).to_sql

推荐答案

我参加聚会有点晚了,但这是我能想出的最佳建议:

I'm a little late to the party, but here's the best suggestion I could come up with:

admins = User.where(:kind => :admin)
authors = User.where(:kind => :author)

admins = admins.where_values.reduce(:and)
authors = authors.where_values.reduce(:and)

User.where(admins.or(authors)).to_sql
# => "SELECT "users".* FROM "users"  WHERE (("users"."kind" = 'admin' OR "users"."kind" = 'author'))"

这篇关于ActiveRecord Arel OR 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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