karmi/tire — pull request #278 by chromeragnarok (2012-03-14 05:05:30+00:00)
Title: Implemented auto reindex when associated model is updated

Hi all,

I've implemented a feature which trigger a reindex when an associated model is updated. For example:

```
class ::AssociatedModel < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks

has_many :articles, :class_name => "ActiveModelArticleWithAssociation", :foreign_key => "article_id"

mapping do
indexes :first_name
indexes :last_name
end
end

class ::ActiveModelArticleWithAssociation < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks

mapping do
indexes :title
indexes :content
indexes :associated_model, :class => AssociatedModel do
indexes :first_name
end
end
end
```

Everytime an instance of AssociatedModel first_name is updated, any referring instance of ActiveModelArticleWithAssociation will be reindexed. Thus keeping the index in sync with the database. The indexing is (preferrably) done through delayed_job. If there's no delayed_job available, it will be reindex on the main application.

Second minor feature that I've added is that nested attribute will be created automatically, based on the mapping. So no need to define a separate to_indexed_json in your class. However, overriding the to_indexed_json would still work as well. At the moment, it only support 1 level of nesting, I don't think it will support any deeper levels at the moment.

Thanks!