ActiveRecord的阿雷尔OR条件 [英] ActiveRecord Arel OR condition

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

问题描述

使用逻辑,而不是或你怎么可以将2个不同的条件是什么?

注意: 2的条​​件产生的轨道范围,并不能轻易变成像其中(X或Y)直接。

简单的例子:

 管理​​员= User.where(:一种=>:管理员)
作者= User.where(:一种=>:作者)
 

这是很容易申请和条件(对于这种特殊情况下是没有意义的):

 (admins.merge作者).to_sql
#=>选择...从...其中一种='管理员'AND KIND =作者
 

但你怎么能生产出具有以下查询2不同阿雷尔关系已有的?

 #=>选择...从...其中一种='管理员'或种类=作者
 

看来(根据阿雷尔自述):

  

目前尚不支持OR运算符

不过,我希望它在这里并不适用,想到写这样的:

 (admins.or作者).to_sql
 

解决方案

我有点迟到了,但这里是我能想出的最好的建议:

 管理​​员= User.where(:一种=>:管理员)
作者= User.where(:一种=>:作者)

管理员= admins.where_values​​.reduce(:和)
作者= authors.where_values​​.reduce(:和)

User.where(admins.or(作者))。to_sql
#=> 选择\用户\。* FROM \用户\WHERE((\用户\\一种\=管理员或\用户\\一种\=作者) )
 

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

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

Simple example:

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

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'

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

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

It seems (according to Arel readme):

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的阿雷尔OR条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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