Dr Blinken

blog, bentosheets and railspages.

How to Search

To add search functionality to your app, you need the following:

Decide where the search should happen. The easiest thing is to add it to an existing index page. In the following example, I’ll add a search to the index of a resource called “survey”.

Search Form

  1. add a test: see commit
  2. add the search form itself:

    <%= form_tag surveys_path, :method => ‘get’ do %> <%= text_field_tag :search, params[:search] %> <%= submit_tag “Search”, :name => nil %> <% end %>

form_tag is an ActionView Helper; you can find the Doc here: form_tag

The Route

is already there if you use the index action for the search. Otherwise create it in config/routes.rb and change surveys_path in the form to the appropriate path.

Again, the test first:

In order to test the search, we need some sample data in our test database. Use FactoryGirl for that. For this and the actual integration test, see the commit.

Here are links to the Capybara Doc:

This is just one simple example for an integration test for the search. You might want to add one or two more tests (e.g. that the second record is present on the page if you don’t do search, that is, that the search actually makes any difference), but not too many. If the search gets more complicated, rather add component tests against the model method implementing the search, see below.

and the implementation:

In the controller index action just delegate to the model:

@surveys = Survey.search(params\[:search\])

and in the model:

def self.search(search)
  if search
    where("title LIKE ?", "%#{search}%")
  else
    all
  end
end

see also the commit.

See the Active Record Querying Rails Guide for a great documentation how you can do searches with ActiveRecord.

You probably won’t read through everything at first, but note that all the methods don’t return Arrays as it might seem, but ActiveRecord::Relation objects, making it possible to chain them together and have ActiveRecord generate efficient SQL queries. Try them out in the console or use the explain method at the bottom of the page to see the actual SQL query performed on the database.