Pollyanna - very simple search for your ActiveRecord models
Pollyanna adds a very simple full text search to your ActiveRecord models. Before saving, searchable models copy strings relevant to the search into a text column. Pollyanna finds results for a query using LIKE patterns in SQL.
We found Pollyanna very useful for search-as-you-type boxes.
Example
class Movie < ActiveRecord::Base
include Pollyanna::Searchable
def search_text
"#{title} #{year} #{director}"
end
end
class MoviesController
def index
@movies = Movie.search(params[:query])
end
end
Making a model searchable
-
Add a text column “search_text” to a model
-
Have the model include
Pollyanna::Searchable
-
Overwrite
search_text
to define which text is indexed upon saving -
Model.search("query goes here")
now gives you a scope for the results of your query. Blank queries return everything.
Searching other columns
If you want to search a column other than search_text
, you may say Movie.search(query, :by => "other_column")
.
How queries are matched
-
Pollyanna matches partial words, so “oo” matches “foo”.
-
Multiple words in a query are AND-ed automatically.
Installation
Pollyanna is a gem, which you can install with
sudo gem install pollyanna
In Rails 2, add the following to your environment.rb
:
config.gem 'pollyanna'
In Rails 3, add the following to your Gemfile
:
gem 'pollyanna'
Rails 3 compatibility
We cannot guarantee Rails 3 compatibility at this point, but we will upgrade the gem when Rails 3 is released.
Credits
Henning Koch