Simple Search Tutorial

Note: This simple search only works for single words or phrases.

In the Model

1. Add the search method to the model

Open the model and add:

codetitle. app/model/grant.rb

  search_condition = "%" + search + "%"
  find(:all, :conditions => ['title LIKE ? OR description LIKE ?', search_condition, search_condition])

Here we defined the variable search_condition. In the definition we used wild cards (%) so that our search could more broad. So for example, you could search for penguin and it would return search results that had both penguin and/or penguins. Next we used the built in find method that returns all the results that match our conditions. In the conditions hash we wrote the variables for our search so that it will find grants based on our search in either the title or description of our grants database.

We add this code to the model although it could also be in the controller because the philosophy of programming strives to keep the controller skinny and the model fat.

In the Controller

2. Create the search action in the controller

codetitle. app/controllers/grants_controller.rb

def search
  @grants = params[:search]

We are calling the method search on the grant model and that’s going to return for us a list of the grants. Our search conditions are in the parameters named search.

In the View
3. Create a partial for the search field. Add to partial:

codetitle. app/views/grants/_search.rhtml

1  <%= form_tag :controller => 'grants', :action => 'search', :method => 'get' do %>
2      <%= text_field_tag :search, params[:search], :id => 'search_field' %>
3      <%= submit_tag "Search", :name => nil %> 
4      <%= link_to_function "Clear", "$('search_field').clear()" %>
5  <% end %> 

Here we are creating a search form that will submit data to the grants controller. Line 1 creates the search form and gets the grants from the search action. Line 2 creates a text field box and the search_field id, which we’ll use later to clear the search box. Line 3 creates a submit tag for the search function. Line 4 creates a function to clear the search box using java script.

4. First, create a simple layout, then add the search function to every page

Open the application.rhtml:

codetitle. app/views/grants/layouts/application.rhtml

  <div id="search">
    <%= render :partial => 'grants/search' %>

This allows our users to easily do a search from any page on our web application without having to return to the homepage.

5. Create a partial for the results page

codetitle. app/views/grants/_search_results.rhtml

    <% @grants.each do |grant| %>
  <li><%= link_to grant.title, 
    :action => 'show', :id =>  %></li>
  <% end %>

Here we are creating an unordered list of the search results in a new webpage. This code calls the action show on the search results so that they can nicely display on the page.

More Resources for searches