Skip to content
jabbrwcky edited this page Apr 17, 2012 · 7 revisions

Rails integration

(This page was contributed by Roger Braun)

If you only want a simple search for all the fields of your Model in your Rails app, you can use this technique. It is easy to extend to other use cases as well.

  1. Add "picky" to your Gemfile

  2. 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
  3. 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
  4. That's it.