开发者

Automatically indexing child model in sunspot (with fields requiring the parent to be saved)

I have a model Author with a has_many relationship to model Book. Books are indexed by sunspot, and have an indexed field :author_name which pulls the name of the Author associated with it.

I have a form that allows you to create an author and add books at the same time via

ac开发者_如何转开发cepts_nested_attributes_for :book

My problem is that when creating a new author with books the new books are not indexed correctly. I believe that when the books are created and the after_save sunspot index is called the associated new author has not yet been committed and so its name does not exist.

What's the best solution for this? I've tried adding an after_commit hook on the author model to index all of the associated books, but when that method loops through the books their ids / associations are nil.


I had to add an after_save hook on the parent model to look up all of the children and save them. Inside that after_save I had to re-lookup all of the books based on ID - otherwise their associated Author was nil.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜