我正在尝试使用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中做的事情。
请帮忙。 感谢
答案 0 :(得分:1)
不幸的是,Mongoid似乎不像ActiveRecord那样支持counter_cache
。
您可以在after_save
模型上使用after_destroy
和Comment
回调来实现此功能,分别递增/递减父级计数器。