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

ril*_*ley 2 activerecord ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

Ale*_*x D 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?
Run Code Online (Sandbox Code Playgroud)

顺便说一下,不要试试这个irb:"read-eval-print"的"print"部分将强制评估记录集.

编辑:我只是想通了,而不是Record.where(true),你可以使用Record.scoped.但是,这在Rails 4中不起作用.