pho*_*1re 178 ruby-on-rails ruby-on-rails-3 rails-activerecord
你如何在Rails 3 ActiveRecord中进行OR查询.我找到的所有示例都只有AND查询.
编辑:自Rails 5以来可以使用OR方法.请参阅ActiveRecord :: QueryMethods
dea*_*rma 204
如果要对一列的值使用OR运算符,可以将数组传递给.where
,ActiveRecord将使用IN(value,other_value)
:
OR
输出:
Model.where(:column => ["value", "other_value"]
Run Code Online (Sandbox Code Playgroud)
这应该相当于.where
单个列
rub*_*nce 149
在Rails 3中,它应该是
Model.where("column = ? or other_column = ?", value, other_value)
Run Code Online (Sandbox Code Playgroud)
这还包括原始sql但我不认为在ActiveRecord中有一种方法可以进行OR操作.你的问题不是一个菜鸟问题.
Dan*_*vin 109
使用ARel
t = Post.arel_table
results = Post.where(
t[:author].eq("Someone").
or(t[:title].matches("%something%"))
)
Run Code Online (Sandbox Code Playgroud)
结果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%'))
Run Code Online (Sandbox Code Playgroud)
Chr*_*ini 56
Rails/ActiveRecord的更新版本可以本机支持此语法.它看起来类似于:
Foo.where(foo: 'bar').or.where(bar: 'bar')
Run Code Online (Sandbox Code Playgroud)
如此拉动请求中所述https://github.com/rails/rails/pull/9052
现在,只需坚持下面的工作:
Foo.where('foo= ? OR bar= ?', 'bar', 'bar')
Run Code Online (Sandbox Code Playgroud)
更新:根据https://github.com/rails/rails/pull/16052,该or
功能将在Rails 5中提供
更新:功能已合并到Rails 5分支
Gre*_*sen 34
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)
Run Code Online (Sandbox Code Playgroud)
San*_*osh 19
Rails 5附带了一种or
方法.(墨迹到文档)
此方法接受一个ActiveRecord::Relation
对象.例如:
User.where(first_name: 'James').or(User.where(last_name: 'Scott'))
Run Code Online (Sandbox Code Playgroud)
Raf*_*lak 14
如果要将数组用作参数,则以下代码适用于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))
Run Code Online (Sandbox Code Playgroud)
更多信息:在Rails 4中使用数组作为参数进行OR查询.
该MetaWhere插件完全是惊人的.
轻松混合OR和AND,在任何关联上加入条件,甚至指定OUTER JOIN!
Post.where({sharing_level: Post::Sharing[:everyone]} | ({sharing_level: Post::Sharing[:friends]} & {user: {followers: current_user} }).joins(:user.outer => :followers.outer}
Run Code Online (Sandbox Code Playgroud)
只需在条件中添加OR即可
Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
126024 次 |
最近记录: |