0

我正在尝试使用 mongodb、mongoid 和 rails。我在 Rails 中有一个简单的任务和评论模型,其中评论嵌入到任务中。现在 Task 具有名为 comment_count 的属性。有没有办法在一次调用中增加计数以及将新评论推送到一起。

任务模型:

class Task
  include Mongoid::Document
  field :name
  field :desc
  field :comment_count, type: Integer, default: 0
  embeds_many :comments
end

评论型号:

class Comment
  include Mongoid::Document
  field :entry
  embedded_in :task
end

以下是我想在一次通话中执行的操作。

1.9.3p194 :025 > task.comments.push(Comment.new(entry: "This is a comment"))
 => [#<Comment _id: 509e1708a490b3deed000003, _type: nil, entry: "First comment">, #<Comment _id: 509e1716a490b3deed000004, _type: nil, entry: "Second comment">, #<Comment _id: 509e1aa3a490b3deed000005, _type: nil, entry: "This is a comment">] 
1.9.3p194 :026 > task.inc(:comment_count, 1)
 => 3 

我实际上打算在单个更新调用中使用多个更新修饰符,如$inc$push$pop等。类似于我们可以直接在 mongo shell 中执行的操作。

请帮忙。谢谢

4

1 回答 1

1

不幸的是,Mongoid 似乎counter_cache不像 ActiveRecord 那样支持。

您可以在模型上使用一个after_save和一个after_destroy回调Comment来实现这一点,分别增加/减少父级的计数器。

于 2012-11-10T13:26:20.043 回答