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

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


当前回答

你可以这样做:

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

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

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

其他回答

在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值

rails + arel,一个更清晰的方式:

# Table name: messages
#
# sender_id:    integer
# recipient_id: integer
# content:      text

class Message < ActiveRecord::Base
  scope :by_participant, ->(user_id) do
    left  = arel_table[:sender_id].eq(user_id)
    right = arel_table[:recipient_id].eq(user_id)

    where(Arel::Nodes::Or.new(left, right))
  end
end

生产:

$ Message.by_participant(User.first.id).to_sql 
=> SELECT `messages`.* 
     FROM `messages` 
    WHERE `messages`.`sender_id` = 1 
       OR `messages`.`recipient_id` = 1

使用activerecord_any_of gem,您可以编写

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

我刚刚从客户端工作中提取了这个插件,它可以让你将作用域与。or结合起来。例如post .published.or. authorred_by (current_user)。Squeel (MetaSearch的更新实现)也很棒,但不支持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分支