轨道 3.0.1 Mongoid (2.0.0.beta.20)
类(class)帖子 embeds_many:评论 字段:comments_count 结束
Class Comment
embedded_in :commentable, :inverse_of => :comments
end
我想选择评论最多的 10 个帖子。为此,我需要 Post 中的 comments_count 字段。但由于我的评论是多态的(Post.comments、Message.comments 等),我不想在 Post 中创建 inc 回调。我不想做的是在 Comment 中创建回调,这将更新 Post 中的 comment_count 字段。
我不知道如何在父文档的字段上的嵌入式文档中执行 inc 操作并从父文档执行此回调
最佳答案
下面是如何从嵌入的多态Comment
增加Post
:
Class Comment
after_create :update_post_comment_count
def update_post_comment_count
if self._parent.class == Post
Post.collection.update( {'_id' => self._parent._id},
{'$inc' => {'comment_count' => 1}} )
end
end
end
我很确定每当创建新 Comment 时都会执行此回调,因此我认为您无需担心从父文档执行它。让我知道它是否有效。
参见 this SO answer还有这个Github issue有关嵌入式文档中回调的更多信息。
关于ruby - Mongoid:从父级上的嵌入式文档运行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386046/