Skip to content
rogerbraun edited this page Jan 26, 2012 · 7 revisions

Rails integration

If you only want a simple full-text search in your Rails app, you can use this technique. It is easy to extend to other use cases as well.

  • Add "picky" to you Gemfile

  • In the model you want to be indexed and searchable, add a search method and an after_save indexer.

class Book < ActiveRecord::Base
  after_save :reindex

  def reindex
    BookIndex.replace self
  end

  # This returns an ActiveRecord relation, so you can still use
  # Kaminari for pagination or other scopes without hitting the
  # database.
  def self.search keys
    # TODO: Picky can not return all ids, so be sure to use a large 
    # value for the maximum amount that is returned.
    ids = (BookSearch.search keys, 1000000).ids
    Book.where("id in (?)", ids)
  end

end
  • Add a config/initializers/picky.rb
if Book.table_exists? then 
  BookIndex = Picky::Index.new :books do
    source Book.all
    
    # This will add all attributes to the index.
    Book.attribute_names[1..-1].each do |cname|
      category cname.to_sym
    end
  end

  BookSearch = Picky::Search.new BookIndex 

  begin
    # Try to load the index from cache.
    BookIndex.load
  rescue
    # Index on first boot or on database changes.
    BookIndex.index 
  end
  
  # Save the index program exit.
  at_exit { BookIndex.dump }
end
  • That's it.

Clone this wiki locally