Search code examples
ruby-on-railsactiverecordransack

Query with ransack: how to get no results by default


I would like my page to have no results by default.

I would like to achieve the same like when I add .none to result but still after parameters are set result are shown. How can i achieve that?

def index
 @search = SomeClass.all
 @items = @search.result.page(params[:page]).per(10)
end

Solution

  • If I understand your question, you want your index page to display no records when you first load the view (and when the filters are empty). This could result in returning too many records and the user would experience a very slow loading page.

    One way to address this is to make sure you execute the search query only if search parameters are passed to the action.

    In your controller

    def index
     # we define the search but we don't execute it right away
     search
     # execute the search query only if search params exists
     items(params[:page],10) if search_params 
    end
    
    private
    
    def items(page,per=10)
      @items ||= search.result(page).per(per)
    end 
    
    def search
      @search ||= SomeClass.search(search_param)
    end
    
    def search_param
      params[:q]
    end
    

    In your view

    Now you can safely reference @search, it will always be defined in your view. On the other hand, @items, might or might not be defined so you have to handle both cases in your view. For example in haml:

    .row
      = @items.nil? ? (render 'no_results') : (render 'results')