16

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

a = true and b = true and ( 0< c <1 or d=1), a, b, c, d 是列。

我可以有类似的东西:

 Route.where(:a => true,
             :b => true,
             :c => 0..1 OR :d=1
             ).all          
4

3 回答 3

18

I may be wrong, but I don't think you could form that query using the Arel-based where function; you'd need to form up the database query string yourself.

Assuming you're using SQLite or Postgres:

Route.where("a = true and b = true and ((c > 0 and c < 1) or d = 1)").all

I haven't tested this code, but I suspect that might do the job for you. Note this is less 'portable' code; if you change the database you're using the query may break.

于 2012-06-09T06:16:14.050 回答
15

在 Rails 4 你也可以做

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

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

于 2014-09-04T19:33:01.933 回答
3

我认为 Rob 关于 arel 不支持 OR 的说法是正确的。从arel 网站

尚不支持 OR 运算符。它将像这样工作:

users.where(users[:name].eq('bob').or(users[:age].lt(25)))

AND 运算符的行为类似。

于 2012-06-13T21:53:50.207 回答