Ruby on rails 3 如何构造查询而不使用activeRecord触发它?

Ruby on rails 3 如何构造查询而不使用activeRecord触发它?,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,我有以下代码: 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 = qu

我有以下代码:

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
不幸的是,每次执行
query=query时都会触发请求。其中(…)

我可以链接所有where子句(
where().where()…
),但是如何保持我的
if
s


有没有办法告诉ActiveRecord不要触发查询?

您可以在
条件
变量中收集所有条件:

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)