Skip to content

Simple search

Mislav Marohnić edited this page Aug 6, 2011 · 1 revision

Ryan Bates of railscasts.com made a screencast on will_paginate. There he creates a simple search form that displays paginated results. Here is what Ryan wrote in the model:

# models/product.rb
def self.search(search, page)
  paginate :per_page => 5, :page => page,
           :conditions => ['name like ?', "%#{search}%"], :order => 'name'
end

But, will_paginate changed slightly since this screencast was recorded. When you create a search form, make sure its method is GET:

<% form_tag request.path, :method => 'get' do %>
  <% content_tag :label do %>
    Search term:
    <%= text_field_tag :search, params[:search] %>
  <% end %>
<% end %>

If your form's action is POST (or any other HTTP method) then the search term won't be applied to subsequent page links. In other words, when you follow the "Next page" or any other page link, the search parameter(s) would be lost.

Search forms that post with GET are better practice, anyway. One of immediate benefits is that users are able to bookmark search results. Caching is another benefit: browsers, proxies, etc. are happy to cache content that was a result of a GET request.