自动索引太阳黑子中的子模型(包含需要保存父模型的字段)
我有一个模型作者,与模型书籍有 has_many 关系。书籍按太阳黑子索引,并有一个索引字段:author_name,它提取与其关联的作者姓名。
我有一个表单,允许您通过以下方式创建作者并同时添加书籍。
accepts_nested_attributes_for :book
我的问题是,当使用书籍创建新作者时,新书籍没有正确索引。我相信,当创建书籍并且调用 after_save sunspot 索引时,关联的新作者尚未提交,因此其名称不存在。
对此最好的解决方案是什么?我尝试在作者模型上添加 after_commit 挂钩来索引所有关联的书籍,但是当该方法循环遍历书籍时,它们的 id/关联为零。
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
accepts_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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我必须在父模型上添加 after_save 挂钩来查找所有子模型并保存它们。在 after_save 中,我必须根据 ID 重新查找所有书籍 - 否则它们的相关作者为零。
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.