自动索引太阳黑子中的子模型(包含需要保存父模型的字段)

发布于 2024-12-02 21:27:40 字数 358 浏览 0 评论 0原文

我有一个模型作者,与模型书籍有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神经暖 2024-12-09 21:27:40

我必须在父模型上添加 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文