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

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


当前回答

我想添加这是一个解决方案搜索一个ActiveRecord的多个属性。自

.where(A: param[:A], B: param[:B])

会搜索A和B。

其他回答

只要在条件中添加一个OR

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

用服装

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%'))

Rails最近将其添加到ActiveRecord中。它将在Rails 5中发布。已致力于掌握:

https://github.com/rails/rails/commit/9e42cf019f2417473e7dcbfcb885709fa2709f89

Post.where(column: 'something').or(Post.where(other: 'else'))

# => SELECT * FROM posts WHERE (column = 'something') OR (other = 'else)

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

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