Index external models with Sunspot/Solr

Lately I wanted to index all tags of ActsAsTaggableOn for full text search and autosuggestions using Solr resp. Sunspot. The ActiveRecord models of ActsAsTaggableOn are unfortunately not directly accessible as they are located in the ActsAsTaggableOn gem. Fortunately that is pretty easy to solve by using metaprogramming techniques. So I added an additional initializer named sunspot_index.rb into the config/initializers directory with the below content.

# config/initializers/sunspot_index.rb
ActsAsTaggableOn::Tagging.class_eval do
  after_save :index_tag
 
  def index_tag
    tag.index
  end
end
 
ActsAsTaggableOn::Tag.class_eval do
  searchable do
    text :name
    integer :count do
      self.taggings.count
    end
  end
end

This adds an Sunspot/Solr index for the tag name and also one for the tag count (how often the tag is used). The tag also gets reindexed when a tagging was added or removed. (Side note: ActsAsTaggableOn uses tag and tagging together to represent a tag of a taggable. Have a look at the ActsAsTaggableOn source for more info, it is very well commented).

One other minor pitfall is that the rake task rake sunspot:reindex does not include the above specified index. That’s because it just looks up the defined indexes of models in the the main model directory. There is an easy solution for this problem, too. Just use the rake task rake sunspot:reindex[,ActsAsTaggableOn::Tag] to index/reindex the external Tag model. (Don’t forget to also index/reindex your normal models by using rake sunspot:reindex.)