Multiple filter criteria in Ruby on Rails

I wanted to allow user to filter records with multiple criteria but each criteria should be could be left blank. I think I came up with a quite scalable and elegant solution.

My controller:

    if params[:code].present? or params[:name].present?
      conditions = []
      conditions << 'code LIKE :code ' unless params[:code].nil? or params[:code].empty?
      conditions << 'name LIKE :name ' if params[:name].nil? or params[:name].empty?
      @stocks = Stock.where(conditions.join(' OR '), {code: "%#{params[:code]}%", name: "%#{params[:name]}%"})
    else
      @stocks = Stock.all
    end

I hope it helps!

Leave a Reply