如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。

Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods


当前回答

MetaWhere插件非常棒。

轻松混合OR's和and 's,任何关联的连接条件,甚至指定OUTER join 's!

Post.where({sharing_level: Post::Sharing[:everyone]} | ({sharing_level: Post::Sharing[:friends]} & {user: {followers: current_user} }).joins(:user.outer => :followers.outer}

其他回答

在Rails 3中,应该是这样

Model.where("column = ? or other_column = ?", value, other_value)

这也包括原始sql,但我不认为有一种方式在ActiveRecord做或操作。你的问题不是新手的问题。

Rails 5添加了或,所以现在在Rails版本大于5的应用程序中更容易做到这一点:

Model.where(column: value).or(Model.where(other_column: other_value)

这也可以处理nil值

只要在条件中添加一个OR

Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])

MetaWhere插件非常棒。

轻松混合OR's和and 's,任何关联的连接条件,甚至指定OUTER join 's!

Post.where({sharing_level: Post::Sharing[:everyone]} | ({sharing_level: Post::Sharing[:friends]} & {user: {followers: current_user} }).joins(:user.outer => :followers.outer}

如果你想在一个列的值上使用OR操作符,你可以传递一个数组到.where, ActiveRecord将使用IN(value,other_value):

Model.where(:column => ["value", "other_value"]

输出:

SELECT `table_name`.* FROM `table_name` WHERE `table_name`.`column` IN ('value', 'other_value')

这应该在单个列上实现与OR相同的效果

Rails/ActiveRecord的更新版本可能原生支持此语法。它看起来类似于:

Foo.where(foo: 'bar').or.where(bar: 'bar')

如此拉请求https://github.com/rails/rails/pull/9052中所述

现在,只要坚持下面的方法就可以了:

Foo.where('foo= ? OR bar= ?', 'bar', 'bar')

更新:根据https://github.com/rails/rails/pull/16052, or特性将在Rails 5中可用

更新:特性已经合并到Rails 5分支