Search code examples
ruby-on-railsrubysearch-form

Ruby on Rails : Search form


Hello I'm developing a simple search form for my rub application.

I've created an action in an existing controller generated by a scaffold:

(rails g scaffold Product name description:text price:decimal)

called search_products and a view called search.html.erb

in the search view I've got the text_field_tag where I insert the parameters for the search (and of course a submit button to send them)

<%= form_tag products_path, :method => 'get' do %>
 <%= text_field_tag :search, params[:search]%>
 <%= submit_tag "Search" %> 
<% end %>

when i press submit the page root to the products_path where i found the list of my searched products.

It seems to be a sort of error in my search_products action because I receive this error:

NoMethodError in ProductsController#index

undefined method `search_products' for #

I post my controller:

def self.search_products(search)
    if search
      where(["name LIKE ?","%#{search}%"])
    else
      all 
    end
  end

  # GET /products
  # GET /products.json
  def index
    @products = Product.search_products(params[:search])
  end

This is one of my first rails applications so sorry for my dumb errors.


Solution

  •  def self.search_products(search)
       if search
         where(["name LIKE ?","%#{search}%"])
       else
         all 
       end
     end
    

    This code is supposed to be in your model code, not controller