Search code examples
ruby-on-railsransack

Disable ransack gem searching all


How to disable ransack gem to search all records in the first request?

I own thousands records and did not want them all to be loaded every time I access the page. I just want to display the search form.

def index
   @search = ransack_params
   @users = ransack_result
end

private
def ransack_params
  User.search(params[:q])
end

def ransack_result
  @search.result(distinct: false)
end

The output of my console shows the following:

Processing by UsersController#index as HTML Parameters: {"utf8"=>"✓", "q"=>{"name"=>""}, "button"=>""}
  Rendering users/index.html.erb within layouts/application
  User Load (0.5ms)  SELECT "users".* FROM "users"

Solution

  • Can do it in two ways.

    1 - Don't iterate through user results if params[:q] is blank. Search query isn't executed until you try to consume the records of the search results relation.

    so you can do like following in your view

    unless params[:q].blank?
      # @search.each do ...
    end
    

    2 - create an empty scope which generates no results

    class User < ActiveRecord::Base
      scope :empty_results, -> { where(id: '-1000') }
    end
    
    def ransack_params
     if params[:q].blank?
       User.empty_results.search
     else
       User.search(params[:q])
     end
    end