Ruby-on-rails Rails 4 是否支持 OR 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17192829/
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
Does Rails 4 have support for OR queries
提问by Arjan
So in Rails 4 the long desired feature to use notqueries has been added.
因此在 Rails 4 中not添加了使用查询的长期期望的功能。
Article.where.not(title: 'Rails 3')
Has similar support been added for orqueries, or are they planning to make it. I couldn't find anything by browsing through the release notes.
是否为or查询添加了类似的支持,或者他们是否计划实现。通过浏览发行说明我找不到任何东西。
Obviously I tried
显然我试过了
Article.where(title: 'Rails 3').or(title: 'Rails 4')
But that does not work.
但这不起作用。
回答by gregates
Article.where(title: ['Rails 3', 'Rails 4'])
is how you'd do that in Active Record.
就是你在 Active Record 中这样做的方式。
It's not possible to replicate any arbitrary SQL query using "Rails-y" syntax. But you can always just pass in literal sql.
不可能使用“Rails-y”语法复制任何任意 SQL 查询。但是你总是可以只传入文字 sql。
So you could also do:
所以你也可以这样做:
Article.where("articles.title = 'Rails 3' OR articles.title = 'Rails 4'")
回答by Fellow Stranger
This now works in Rails 5:
这现在适用于 Rails 5:
Article.where(title: 'Rails 3').or(Article.where(title: 'Rails 4'))
回答by Pritesh Jain
The most common alternative is already answer by @gregates
最常见的选择已经由@gregates 回答
Recently there has been pull request in rails source
最近在rails源中出现了pull request
Add #any_ofquery method to active_recordWhich adds or functionality to activerecord
将#any_of查询方法添加到 active_record哪个添加或功能到 activerecord
the contributor has already created a gem incase its not accepted
贡献者已经创建了一个 gem incase 它不被接受
its rails 3.2 and 4 compatible
它的导轨 3.2 和 4 兼容
https://github.com/oelmekki/activerecord_any_of
https://github.com/oelmekki/activerecord_any_of
I havent tried it yet but soon wish to use it looks good to me.
我还没有尝试过,但很快希望使用它对我来说看起来不错。
回答by Rob Richey
I know that this is an old thread, but anyone else looking for a solution to this problem might find this code helpful:
我知道这是一个旧线程,但其他任何正在寻找解决此问题的方法的人都可能会发现此代码很有帮助:
Article.where(title: ["Rails 3", "Rails 4"])
Maybe that will help you get someone going in the right direction without having to risk sql injection.
也许这会帮助你让某人朝着正确的方向前进,而不必冒 sql 注入的风险。
回答by Arjan
It seems that the rails master branch is now supporting OR queries. https://github.com/rails/rails/pull/16052
似乎 rails master 分支现在支持 OR 查询。https://github.com/rails/rails/pull/16052
I assume it will be in the framework with the next major release.
我认为它将在下一个主要版本的框架中。
回答by Nicolas Maloeuvre
Rails 5 will support it but you can use this backport for Rails 4.2 : https://github.com/Eric-Guo/where-or
Rails 5 将支持它,但您可以将此向后移植用于 Rails 4.2:https: //github.com/Eric-Guo/where-or

