Sunspot: parent model strength index when updating child model

I use Sunspot to generate many indexes and reviews of my applications.

In this application, I have 2 models that have a parent / child relationship to each other. With Sunspot, I index the number of children the parent has, so this is available for sorting, scoping, etc.

However, when I change the child model, the parent model does not automatically receive reindexing (since it has not changed). Coercion of the parent. Passing through call_back for the child also does not force the index.

So, before I start hacking:

What would be the best way to force an index on a parent class in Sunspot when modifying / adding a child model?

+5
source share
1 answer

I had the same problem right now. After looking at the API documentation for Sunspot , it seems that Sunspot extends the models with a method index()that causes the instance to be re-indexed.

Given this, you just need to connect to the after_save return signal of the child model to re-index the parent when it is stored in the database:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  after_save :reindex_parent!

  def reindex_parent!
    parent.index
  end
end
+7
source

All Articles