是否有一种方法在Rails 3中有条件地合并记录条件而不做字符串或数组合并?
例如: conditions = #?
if !params[:x].blank?
# add a condition
end
if user.role?(:admin)
# add a condition
end
if params[:y]
# add a condition
end
etc
result = Record.where(xx).group(:id).order(some_var)
# xx would merge all then group and order
Easy:
# oh, the joy of lazy evaluation...
result = Record.where(true) # I'd like to do Record.all, but that fetches the records eagerly!
result = result.where("...") if params[:x].present?
result = result.where("...") if user.role?(:admin)
result = result.where("...") if params[:y].present?
顺便说一下,不要在irb
中尝试这样做:"read-eval-print"的"print"部分将强制计算记录集。
EDIT:我刚刚发现你可以用Record.scoped
代替Record.where(true)
。但是,这在Rails 4中不起作用。