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

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


当前回答

如果你想使用数组作为参数,下面的代码在Rails 4中工作:

query = Order.where(uuid: uuids, id: ids)
Order.where(query.where_values.map(&:to_sql).join(" OR "))
#=> Order Load (0.7ms)  SELECT "orders".* FROM "orders" WHERE ("orders"."uuid" IN ('5459eed8350e1b472bfee48375034103', '21313213jkads', '43ujrefdk2384us') OR "orders"."id" IN (2, 3, 4))

更多信息:在Rails 4中使用数组作为参数的OR查询。

其他回答

使用activerecord_any_of gem,您可以编写

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

只要在条件中添加一个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%'))

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 4中工作:

query = Order.where(uuid: uuids, id: ids)
Order.where(query.where_values.map(&:to_sql).join(" OR "))
#=> Order Load (0.7ms)  SELECT "orders".* FROM "orders" WHERE ("orders"."uuid" IN ('5459eed8350e1b472bfee48375034103', '21313213jkads', '43ujrefdk2384us') OR "orders"."id" IN (2, 3, 4))

更多信息:在Rails 4中使用数组作为参数的OR查询。