Question

This is my _search_box.html.erb file

<%= form_tag "/catalog/search", :method => "get" do %>
  <%= text_field_tag :q %> 
  <%= submit_tag 'Search' %>
<% end %>

which is rendered in search.html.erb:

<%= render :partial => 'search_box' %>
<% if @products %>
    <%= render(:partial => "products") %>
<% end %>

And this is my search method for the CatalogController class:

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

I get this error when I access /catalog/search

NoMethodError in CatalogController#search

undefined method `stringify_keys!' for "":String

I am using meta_search gem for the search.

What is happening?

Was it helpful?

Solution

You should not be putting the value of what you want to search for directly into q. q is supposed to be a hash of all your search conditions. For example:

q: { name_contains: 'something interesting', price_less_than: '100' }

Like this the search conditions come into the controller in params[:q]. If you don't want to use this hash and have just a single search field for the product's name say, then change your view to be something like this if you want to do a substring match:

<%= text_field_tag :name_contains %>

or this, if you want to do an exact match:

<%= text_field_tag :name_equals %>

and change your controller search method to be:

def search
  @search = Product.search params
  ...

However, if you use this approach then be careful you never have any non-search related parameters coming in otherwise they will go to MetaSearch too, which is why normally you should use the q hash.

Finally, the MetaSearch gem is quite old and no longer maintained now. If you are just starting with setting up searching, maybe take a look at Ransack instead which in its simple mode is basically a rewrite of MetaSearch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top