Ruby on rails Rails 3或arel链/合并SQL条件有条件

Ruby on rails Rails 3或arel链/合并SQL条件有条件,ruby-on-rails,activerecord,arel,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

在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
简单:

顺便说一下,不要在
irb
中尝试此操作:“read eval print”的“print”部分将强制对记录集进行评估


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

没问题。tenderlove的arel图书馆使这样的事情成为可能——我认为图书馆是一个真正的杰作。
# 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?