我有这段代码:
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不要触发查询?
答案 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)