【问题标题】:Mongoid: Run callback from embedded document on parentMongoid:从父级嵌入文档运行回调
【发布时间】:2011-05-22 03:00:42
【问题描述】:

导轨 3.0.1 Mongoid (2.0.0.beta.20)

班级帖子 embeds_many :cmets 字段:cmets_count 结束

Class Comment
 embedded_in :commentable, :inverse_of => :comments
end

我想选择 10 个评论最多的帖子。为此,我需要 Post 中的 cmets_count 字段。但由于我的评论是多态的(Post.cmets、Message.cmets 等),我不想在 Post 中创建 inc 回调。我不想做的是在 Comment 中创建回调,它将更新 Post 中的 comment_count 字段。

我不知道如何在来自父文档的字段上的嵌入文档中执行 inc 操作并从父文档执行此回调

【问题讨论】:

    标签: ruby mongodb mongoid


    【解决方案1】:

    这里是如何从嵌入的多态 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
    

    我很确定每当创建新的评论时都会执行此回调,因此我认为您不必担心从父文档执行它。让我知道它是否有效。

    请参阅this SO answerGithub issue,了解有关嵌入式文档中回调的更多信息。

    【讨论】:

    • 谢谢你的代码为我工作:]。你有 _parent 方法描述的 mongodb 文档链接吗?
    • 我似乎找不到任何有关 _parent 的文档。我自己通过反复试验找到了它。
    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    相关资源
    最近更新 更多