0

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' %>
dabadaba
  • 9,064
  • 21
  • 85
  • 155
  • because when your params search blank then @search is nil. why are you using form_for here. just use form_tag simply – LHH Apr 18 '14 at 15:28
  • there are a couple of ways you can do it here: http://stackoverflow.com/questions/5827910/how-to-set-a-0-result-in-meta-search-before-user-pressing-a-search-button –  Apr 18 '14 at 15:59

1 Answers1

1

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
LHH
  • 3,233
  • 1
  • 20
  • 27
  • the `meta_search` gem works with the names of the fields. it needs to be `form_for` so it creates a hash in `search` – dabadaba Apr 18 '14 at 15:33
  • Then you can do one thing here if your params search is blank then simply initialize your Product model like this @search = Product.new. i hope this should work – LHH Apr 18 '14 at 15:35
  • where should I do that? in the controller? – dabadaba Apr 18 '14 at 15:38