Benjamin Crouzier
Benjamin Crouzier

Reputation: 41895

How to construct a query without triggering it with activeRecord?

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 ifs ?

Is there a way to tell ActiveRecord not to trigger the query ?

Upvotes: 0

Views: 53

Answers (1)

Oleg Haidul
Oleg Haidul

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

Related Questions