如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。
Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods
如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。
Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods
当前回答
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)
其他回答
如果你想在一个列的值上使用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 5附带了一个or方法。(链接到文档)
该方法接受ActiveRecord::Relation对象。例如:
User.where(first_name: 'James').or(User.where(last_name: 'Scott'))
使用activerecord_any_of gem,您可以编写
Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')
如果你想使用数组作为参数,下面的代码在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查询。
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)