Reputation: 41895
I have this code:
def build_query(options)
query = User
query = query.where('first_condition')
query = query.where('second_condition')
query = query.where('items.category_id = ?', category) if (options[:category])
if options[:location]
query = query.where('users.location = ?', options[:location])
end
query = query.order('users.current_sign_in_at DESC')
query = query.limit(MAX_RESULTS)
return query
end
Unfortunately, a request is trigerred each time I do query = query.where(...)
I could just chain all where clauses (where().where()...
), but then how do I keep my if
s ?
Is there a way to tell ActiveRecord not to trigger the query ?
Upvotes: 0
Views: 53
Reputation: 3732
You can collect all conditions in conditions
variable:
conditions = {}
conditions.merge('first_condition') if ...
conditions.merge('second_condition') if ...
# snip
User.where(conditions).order('users.current_sign_in_at DESC').limit(MAX_RESULTS)
Upvotes: 2