如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。
Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods
如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。
Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods
当前回答
Rails 5附带了一个or方法。(链接到文档)
该方法接受ActiveRecord::Relation对象。例如:
User.where(first_name: 'James').or(User.where(last_name: 'Scott'))
其他回答
我刚刚从客户端工作中提取了这个插件,它可以让你将作用域与。or结合起来。例如post .published.or. authorred_by (current_user)。Squeel (MetaSearch的更新实现)也很棒,但不支持OR作用域,因此查询逻辑可能有点多余。
用服装
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%'))
使用activerecord_any_of gem,您可以编写
Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')
Rails 5附带了一个or方法。(链接到文档)
该方法接受ActiveRecord::Relation对象。例如:
User.where(first_name: 'James').or(User.where(last_name: 'Scott'))
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}