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

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


当前回答

使用activerecord_any_of gem,您可以编写

Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')

其他回答

你可以这样做:

Person.where("name = ? OR age = ?", 'Pearl', 24)

或者更优雅一点,安装rails_or gem并像这样做:

Person.where(:name => 'Pearl').or(:age => 24)

只要在条件中添加一个OR

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

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分支

Rails 5附带了一个or方法。(链接到文档)

该方法接受ActiveRecord::Relation对象。例如:

User.where(first_name: 'James').or(User.where(last_name: 'Scott'))

用服装

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

结果SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))