繁体   English   中英

Rails: Or & and in Rails ActiveRecord where 子句

[英]Rails: Or & and in Rails ActiveRecord where clause

我正在使用 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          

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

假设您使用 SQLite 或 Postgres:

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

我还没有测试过这段代码,但我怀疑这可能适合你。 请注意,这是不太“可移植”的代码; 如果您更改正在使用的数据库,则查询可能会中断。

在 Rails 4 中你也可以做

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

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

我认为Rob 是正确的,因为arel 还不支持OR。 arel 网站

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

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

AND 运算符的行为类似。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM