user2784630
user2784630

Reputation: 806

Why does my search show all results with searching?

I setup a search on my Products index page with PgSearch and Will-Paginate like this:

ProductsController

def index
  @products = Product.text_search(params[:query]).page(params[:page]).per_page(5)
end

Products Model

 include PgSearch
 pg_search_scope :search, 

 def self.text_search(query)
   if query.present?
     search(query)
   else
     scoped
   end
 end

Product index page

<%= form_tag products_path, method: :get do %>
  <%= text_field_tag :query, params[:query] %>
  <%= submit_tag "Search", name: nil %>
<% end %>

<% if @products.blank? %>
  No Results
<% else %>
  <% @products.each do |product| %>
   <%= product.name %>
  <% end %>
<% end %>

But the problem I'm having now is that when I go to the Product index page, it shows all of the products when I want it to show nothing until a search is done. If the search is blank, return No Results but when you first hit the page it should show nothing. How would this be done?

Upvotes: 0

Views: 357

Answers (3)

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

You probably want to only run a text_search when a search parameter is present. You can put this logic into the view, the controller, or in the model.

In the view

<% if params[:query].present? %>
  <% if @products.blank? %>
    No Results
  <% else %>
    <% @products.each do |product| %>
      <%= product.name %>
    <% end %>
  <% end %>
<% end %>

In the controller

def index
  if params[:query].present?
    @products = Product.text_search(params[:query]).page(params[:page]).per_page(5)
  else
    @products = Product.none # NOTE: Rails 4 only
  end
end

In the model

# create a new method to encapsulate this search logic then use it in the controller
def self.search(value)
  if value.present?
    Product.text_search(value)
  else
    Product.none # NOTE: Rails 4 only
  end
end

The old saying goes "fat model, skinny controller" so you might want to opt for the model method which will keep your controller and views simpler.

Upvotes: 2

lsaffie
lsaffie

Reputation: 1814

Although I'm not familiar with how pg search works, you could do something like this in your method.

It's a nice refactoring as well as it avoids checking for existence and making decisions on params (code smell)

def self.text_search(query = "")
     search(query)
end

As I said, not sure how pg_search works. Maybe when you browse for nothing, it returns all records. If that's the case, you can just have it return an empty array. Something like this would do

 def self.text_search(query)
    return [] if query.nil?
    search(query)
 end

Upvotes: 1

kddeisz
kddeisz

Reputation: 5192

Put your display logic inside an if statement:

<% if params[:query].present? %>
  <% if @products.blank? %>
    No Results
  <% else %>
    <% @products.each do |product| %>
      <%= product.name %>
    <% end %>
  <% end %>
<% end %>

Upvotes: 1

Related Questions