Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reindex just one particular record with sunspot

I have two models

class User < ActiveRecord::Base
  has_many :posts

  searchable do
    text :post_titles
  end

  def post_titles
    posts.map &:title
  end
end

class Post < ActiveRecord::Base
  belongs_to :user
end

the problem is that when I update title of the Post sunspot doesn't update index for related user and it is not searchable by new data. If I do User.index it solves problem but takes too much time. Are there any better solutions to update parent record index on child record change(like reindex just parent record and not all users)?

like image 368
Bohdan Avatar asked May 04 '12 16:05

Bohdan


1 Answers

Sunspot provides an instance index() method, for indexing one record.

What I did was

 class Post 

   belongs_to :user
   after_save :update_user_index

 private

   def update_user_index
     user.index
   end
end

If you are running this in console, and want to see results immediately, call Sunspot.commit

like image 182
Bohdan Avatar answered Oct 09 '22 10:10

Bohdan