Search code examples
ruby-on-railsrubysearchlogic

How to have searchlogic initialize with no records


I'm using Searchlogic in a model with tens of thousands of records and don't want to initially display them all the first time the search page loads. How do I get an empty search object from searchlogic if there are no :search params?

  def search
    @products = []
    if params[:search] && !params[:search].blank?
      @search = Product.searchlogic(params[:search])
    else
      @search = Product.searchlogic(....What goes here to get an empty searchlogic object?...)
    end
    @products = @search.all
  end

Solution

  • Change your logic to this:

    def search
        @products = []
        @search = params[:search] && !params[:search].blank? ?
            Product.searchlogic(params[:search]) : nil
        @products = @search.all unless @search.nil?
    end
    

    Granted you could keep your if statement like so:

    def search
        @products = []
        @search = nil
        if params[:search] && !params[:search].blank?
            Product.searchlogic(params[:search])
        end
        @products = @search.all unless @search.nil?
    end