Question

I am using the meta_search gem to search products in my catalog. However, the first time I enter the search page or I send a blank value, the search is made and all the products are returned and listed.

I am trying to prevent this checking that the value of the search input is not nil or "" so the search is performed only when something is actually typed in the text field.

This is my search.html.erb file:

<%= render :partial => 'search_box' %>
<% if @products %>
    <p>The search "<%= params[:search][:name_contains] %>" returned <%= pluralize @products.size, "result" %>:</p>
    <%= render(:partial => "products") %>
<% end %>

_search_box.html.erb:

<%= form_for @search, :url => "/catalog/search", :html => {:method => :get} do |f| %>
  <%= f.label :Name %>  
  <%= f.text_field :name_contains %>
  <%= f.submit 'Search' %>
<% end %>

The search method of the CatalogController:

  def search
    if params[:search]
      @search = Product.search(params[:search])
      @products = @search.all
      unless @products.size > 0
        flash.now[:notice] = "No results"
      end
    end
  end

When I browse to /catalog/search I get the following error:

 NoMethodError in Catalog#search

Showing /*****/app/views/catalog/_search_box.html.erb where line #1 raised:

undefined method `model_name' for NilClass:Class

Extracted source (around line #1):

1: <%= form_for @search, :url => "/catalog/search", :html => {:method => :get} do |f| %>
2:   <%= f.label :Nombre %> 
3:   <%= f.text_field :name_contains %>
4:   <%= f.submit 'Search' %>
Was it helpful?

Solution

try this and i think in this way your @search will always be found

def search
  @search = Product.search(params[:search])
  if params[:search]
    @products = @search.all
    flash.now[:notice] = "No results" unless @products.size > 0
   end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top