2

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
4

1 回答 1

5

简单的:

# 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”部分将强制评估记录集。

编辑:我刚刚发现Record.where(true)你可以使用Record.scoped. 不过,这在 Rails 4 中不起作用。

于 2013-04-30T07:51:26.887 回答