简体   繁体   中英

multiple optional conditions in query + active record

I m using rails 3.1.11 with mysql. Consider a User(name, role, city) and Project(name) model . I want to collect users with role 'admin' from 'Pune' or 'manager' from 'Mumbai'.

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. How can i collect the above data in a single call? Mongoid has any_of for similar queries. 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:

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

The curly braces signal the use of squeel, which also provides the & and | operators for AND and OR. I think this looks much easier to read and maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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