0

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 ?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.