如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。
Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods
如何在Rails 3 ActiveRecord中进行OR查询。我找到的所有示例都只有AND查询。
Edit: OR方法从Rails 5开始可用。看到ActiveRecord:: QueryMethods
当前回答
用服装
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)
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}
用服装
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的多个属性。自
.where(A: param[:A], B: param[:B])
会搜索A和B。
你可以这样做:
Person.where("name = ? OR age = ?", 'Pearl', 24)
或者更优雅一点,安装rails_or gem并像这样做:
Person.where(:name => 'Pearl').or(:age => 24)