Sunspot: force index of parent model when updating child model
Asked Answered
B

1

5

I am using Sunspot to generate alot of my apps indexes and overviews.

In this app i have 2 models which have a parent/child one-to-many relationship. With Sunspot I index the number of childs a parent has, so this is available for sorting, scoping etc.

However, when I change the child model the parent model does not automatically get reindexed (as it hasn't changed). Forcing a parent.save through a call_back on the child doesn't force the index either.

So before I start hacking away:

What would be the best way to force an index action on the parent class in Sunspot when a child model gets changed/added?

Bab answered 19/6, 2011 at 12:10 Comment(0)
C
7

I was having the same problem right now. After looking into the API documentation for Sunspot, it seems that Sunspot extends models with a method index() that forces an instance to be reindexed.

With this in mind, it should be just a matter of hooking into the after_save callback of the child model, to reindex the parent when this is stored onto 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
Chalfant answered 30/8, 2011 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.