ruby - Mongoid:从父级上的嵌入式文档运行回调

标签 ruby mongodb mongoid

轨道 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/

相关文章:

ruby-on-rails - 如何在 Rails 中将 Squeel 与 hstore 一起使用

linux - MongoDB:Windows 上不支持 unix 套接字

windows - 为什么我的 mongo 查询不只使用索引?

ruby-on-rails - Mongoid w/Rails,attr_accessible --> "No method found"

ruby-on-rails - 用 mongoid 重命名模型

jquery - 将错误列表从Sinatra传递到jQuery的错误处理程序?

ruby-on-rails - 如何在大型 JSON 数组中搜索并通过多个键查找记录

ruby-on-rails - 如何(或我可以)在寻找错误时临时破解 gem?

python - 结合 Python 和 Ruby 扩展模块

node.js - Mongoose Model.find() 参数问题