Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ransack: start with blank index/no results

Just started using Ransack and i'm loving it. But desperate to know how to start with a blank index, with no results? forcing the user to use the search form. Here what the controller looks like so far.

meals_controller.rb

 def index
    @search = Meal.search(params[:q])
    @meals = @search.result
 end

edit -

Some how this worked and i'm not sure how

meals_controller.rb

 class MealsController < ApplicationController
 before_filter :set_search

 def index
   if params[:q].blank?
     @q = Meal.none.search
   else
     @q = Meal.search params[:q]
   end
     @meals = @q.result
 end

 def set_search
  @search=Meal.search(params[:q])
 end  
end
like image 446
Samuel Avatar asked Mar 21 '23 09:03

Samuel


1 Answers

I don't like the use of a blank scope as you're querying unnecessarily.

I use the following approach instead:

# If no search params, default to empty search
if params[:q] && params[:q].reject { |k, v| v.blank? }.present?
  @q = User.search(params[:q])
  @users = @q.result
else
  @q = User.search
  @users = []
end

Then you can still use @q for your search_form_for in the view but without the querying by default.

like image 123
mwalsher Avatar answered Mar 27 '23 22:03

mwalsher