Ransack: start with blank index/no results
Asked Answered
P

2

5

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
Pulchia answered 3/3, 2014 at 23:3 Comment(1)
You seem to mix convention of ransack (@q) and the predecessor metasearch (@search)Sidecar
S
4

Update:

As @Petercopter noted:
Since Rails 4 there is a native scope none that doesn't even touch the DB. It returns an empty ActiveRecord::Relation.

Old answer:

I use a fake scope named none, that returns no records like where('1=0').
Then write

def index
  if params[:q].blank?
    @q = Meal.none.search # so you have a ransack search
  else
    @q = Meal.search params[:q]
  end
  @meals = @q.result
end

Addition:

in your view you need:

<%= search_form_for @q, url: meals_path, html: {method: :get} do %>
  ...
<% end %>
Sidecar answered 3/3, 2014 at 23:13 Comment(4)
Im afraid your line of code threw this error back No Ransack::Search object was provided to search_form_for!Pulchia
see parameter of search_form_for. I added a view partial.Sidecar
Make sure you use @q as parameter for search_form_for not @search.Sidecar
none was added to core Rails, so this totally works, thanks!Geode
P
4

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.

Partite answered 26/2, 2015 at 20:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.