SimpleSearch

A rather unimaginatively named gem designed to provide simple search functionality to ActiveRecord-backed models and, more usefully, views.

Given a model Widget that belongs_to a WidgetType, shouldn’t you be able to do something like this …

<% form_for :search, @search, :html => {:method => :get} do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :widget_type_name_starts_with %>
  <%= f.text_field :widget_type_name_starts_with %>
  <%= f.submit %>
<% end %>

… to create a search form?

Yes. Yes, you should.

Example

Let’s say you’re going to add a search form to your index page like the one above.

In your controller:

Grab the search params or set a default.

search = params[:search] || {}

Merge in any additional criteria, or add an association to the search. Here, I only want to find Widgets that are less than a week old, and I want to be able to search on attributes of the Widget’s WidgetType as well.

@search = SimpleSearch::Search.new(
  Widget,
  search.merge(:created_at_from => 1.week.ago, :search_associations => :widget_type)
)

This will do a full search, and use pagination. All options are passed through to find or paginate (will_paginate), as required.

@widgets = @search.search(:page => params[:page])

Or if you just want to count the records that would be matched.

@count = @search.count

Then in your view:

<% form_for :search, @search, :html => {:method => :get} do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :widget_type_name_starts_with %>
  <%= f.text_field :widget_type_name_starts_with %>
  <%= f.submit %>
<% end %>

Remember, searches are idempotent so to appease the HTTP gods (and make it easy to bookmark search results) they should be executed with GET.

That should get you started, for now. Read up on SimpleSearch::Search for more details, and keep in mind that this gem was extracted from code designed to serve a specific purpose – it has not spent much time in the wild, so you may (will) find bugs. Please let me know about them.

Copyright © 2010 Ernie Miller. See LICENSE for details.