或者&在Rails ActiveRecord where子句中

Web*_*rit 11 activerecord ruby-on-rails ruby-on-rails-3

我正在使用Rails 3.2,我有一个数据库表,我想在其中找到符合以下条件的所有行:

a = true且b = true且(0 <c <1或d = 1),a,b,c,d为列.

我可以有类似的东西:

 Route.where(:a => true,
             :b => true,
             :c => 0..1 OR :d=1
             ).all          
Run Code Online (Sandbox Code Playgroud)

Rob*_*ice 15

我可能错了,但我不认为你可以使用基于Arel的where函数形成该查询; 您需要自己构建数据库查询字符串.

假设您使用的是SQLite或Postgres:

Route.where("a = true and b = true and ((c > 0 and c < 1) or d = 1)").all
Run Code Online (Sandbox Code Playgroud)

我没有测试过这段代码,但我怀疑可能会为你完成这项工作.请注意,这不是"便携"代码; 如果您更改数据库,您使用的查询可能会中断.

  • `where('a =:true和b =:true和((c>:lo和c <:hi)或d =:d',:true => true,:lo => 0,:hi => 1 ,:d => 1)`会更安全,不同的数据库对"true"使用不同的东西.甚至`.where(:a => true,:b => true).where('c>:lo和c <:hi)或d =:d',...)`. (3认同)

小智 11

在Rails 4中你也可以这样做

Route.where(:a => true,:b => true,:c => [1,2]).all

这将找到c为1或2的位置.