Search code examples
ruby-on-railsactiverecordarel

Rails 3 or arel chain/merge SQL conditions conditionally


Is there a way in Rails 3 to merge record conditions conditionally without doing string or array merging?

For example:

    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

Solution

  • 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?
    

    By the way, don't try this in irb: the "print" part of "read-eval-print" will force evaluation of the record set.

    EDIT: I just figured out that instead of Record.where(true), you could use Record.scoped. This won't work in Rails 4, though.