有条件地Rails 3或arel链/合并SQL条件

时间:2013-04-30 07:48:41

标签: ruby-on-rails activerecord arel

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

1 个答案:

答案 0 :(得分: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中不起作用。