Ruby-on-rails Or & and in Rails ActiveRecord where 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10958844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Or & and in Rails ActiveRecord where clause
提问by Webspirit
I'm using Rails 3.2 and I've got a database table in which I want to find all the rows that match the following criteria:
我正在使用 Rails 3.2 并且我有一个数据库表,我想在其中找到符合以下条件的所有行:
a = true and b = true and ( 0< c <1 or d=1), a, b, c, d are columns.
a = true and b = true and ( 0< c <1 or d=1), a, b, c, d 是列。
Can I have something like:
我可以有类似的东西:
Route.where(:a => true,
:b => true,
:c => 0..1 OR :d=1
).all
回答by Rob d'Apice
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.
我可能错了,但我认为您不能使用基于 Arel 的 where 函数来形成该查询;您需要自己形成数据库查询字符串。
Assuming you're using SQLite or Postgres:
假设您使用 SQLite 或 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.
我还没有测试过这段代码,但我怀疑这可能适合你。请注意,这是不太“可移植”的代码;如果您更改正在使用的数据库,则查询可能会中断。
回答by user2031423
In Rails 4 you can also do
在 Rails 4 中你也可以做
Route.where(:a => true,:b => true,:c => [1,2]).all
Route.where(:a => true,:b => true,:c => [1,2]).all
This will find where c is 1 or 2.
这将找到 c 是 1 或 2 的位置。
回答by pepe
I think Rob is right about arel not supporting OR yet. From the arel site:
我认为 Rob 是对的,关于 arel 不支持 OR 的说法是正确的。从arel 网站:
The OR operator is not yet supported. It will work like this:
尚不支持 OR 运算符。它会像这样工作:
users.where(users[:name].eq('bob').or(users[:age].lt(25)))
The AND operator will behave similarly.
AND 运算符的行为类似。

