Sunspot: force index of parent model when updating child model
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 f开发者_Python百科orce an index action on the parent class in Sunspot when a child model gets changed/added?
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
精彩评论