Simple search

Ryan Bates of railscasts.com recorded the will_paginate screencast. In it, he creates a simple search form that displays paginated results. Here is what Ryan wrote in the model, for example:

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

But, the plugin changed 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 click 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. Other benefits are caching: browsers (and proxies, backends, etc.) are happy to cache content that was a result of a GET request.

Last edited by mislav, 4 months ago
Versions: