如何在不使用activeRecord触发查询的情况下构造查询?

时间:2013-09-17 09:33:03

标签: 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 = 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().where()...),但是如何保留if

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

1 个答案:

答案 0 :(得分:2)

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

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)