简体   繁体   English

查询+活动记录中的多个可选条件

[英]multiple optional conditions in query + active record

I m using rails 3.1.11 with mysql. 我在MySQL上使用Rails 3.1.11。 Consider a User(name, role, city) and Project(name) model . 考虑一个User(名称,角色,城市)和Project(名称)模型。 I want to collect users with role 'admin' from 'Pune' or 'manager' from 'Mumbai'. 我想从“浦那”收集角色为“ admin”的用户, 或者从“孟买”收集角色为“ manager”的用户。

User
has_and_belongs_to_many :projects, uniq: true

Project
has_and_belongs_to_many :users, uniq: true

the query that use is 使用的查询是

users = []
users <<  User.where(role: 'admin', location: 'Pune') 
users <<  User.where(role: 'manager', location: 'Mumbai')
Project.first.users << users

which fires 2 queries. 触发2个查询。 How can i collect the above data in a single call? 如何在一次通话中收集以上数据? Mongoid has any_of for similar queries. Mongoid对于类似查询具有any_of http://two.mongoid.org/docs/querying/criteria.html#any_of . http://two.mongoid.org/docs/querying/criteria.html#any_of I wouldnt prefer to collect all users and then filter. 我不想收集所有用户,然后进行过滤。

你可以做

User.where(["(role = ? and location = ?) or (role = ? and location = ?)", 'admin', 'Pune', 'manager', 'Mumbai'])

If you use the squeel gem, you can make this much nicer: 如果您使用squeel gem,则可以做得更好:

User.where{(role = 'admin') & (location = 'Pune') | (role = 'manager') & (location = 'Mumbai')}

The curly braces signal the use of squeel, which also provides the & and | 花括号指示使用squeel,它也提供&和| |。 operators for AND and OR. AND和OR的运算符。 I think this looks much easier to read and maintain. 我认为这看起来更容易阅读和维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM