Friday, April 18, 2008

ActsAsFerret and computed ferret fields

The ActsAsFerret plugin automatically indexes your model when saving.

The acts_as_ferret method takes a whole slew parameters which includes the fields to be indexed. For example say we have a User model:

 acts_as_ferret :fields => {    
:last_name => {:boost => 10,:store => :yes},
:first_name => {:boost => 1, :store => :yes},
:title => {:boost => 1, :store => :yes},
:introduction => {:boost => 10,:store => :yes}
}, :ferret => {:or_default => true}, :remote => true


This will add last_name, first_name, title and introduction to the index. These fields are just database columns. The symbol for field is really just a method call and so this how we can add computed or nested ferret fields for indexing.

Suppose the user has a set tags with a simple 'has_many :tags' declaration.

Then we can create a simple method in the user model like this.
def user_tags
tags.map(&:name).join(',')
end


and add this method(field) to the acts_as_ferret method

  acts_as_ferret :fields => {    
:last_name => {:boost => 10,:store => :yes},
:first_name => {:boost => 1, :store => :yes},
:title => {:boost => 1, :store => :yes},
:introduction => {:boost => 10,:store => :yes},
:user_tags => {:boost => 10,:store => :yes}
}, :ferret => {:or_default => true}, :remote => true


Now we have the user's tags in the User index.

No comments: