Full text search using Ferret (acts_as_ferret) with rails

25 10 2007

I recently started working with acts_as_ferret so I thought to put together a little how to:

Assuming you already have ruby on rails environment set up

1) To install it run gem install ferret
this will prompt you to select a gem for your platform

2) go to your rails project root directory and run
script/plugin install svn://projects.jkraemer.net/acts_as_ferret/tags/stable/acts_as_ferret

3) Add require 'acts_as_ferret' to your config/environment.rb

4) Resart your app

To add full text search capability to a model simply add this within your model

acts_as_ferret

To add full text search capability to a model but on some specific attributes/field_names add this

acts_as_ferret :fields => [ :author, :content ]

How to perform search?

If your model name is location then you can use

Location.find_by_contents(search_criteria)

Note: If you have very large number of records then it might take a while to run your search for the first time as it indexes all the records

If you want to use pagination or multiple models then use
Location.find_with_ferret query, :page => params[:page], :per_page => 10,
:multi => [ Model_2, Model_3 ]

I will be adding some advanced stuff later on …


Sign up and be a part of SPhred.com and don’t forget to invite your friends ;o)