ActiveRecord的阿雷尔OR条件雷尔、条件、ActiveRecord、OR

2023-09-08 15:41:31 作者:你前任i

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

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

简单的例子:

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

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

 (admins.merge作者).to_sql
#=>选择...从...其中一种='管理员'AND KIND =作者
 
Model, Orm, Dao 和 Active Record 的异同点

但你怎么能生产出具有以下查询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'))"