2012-11-10 13 views
0

的文檔,我試圖用MongoDB的,mongoid和軌試驗。我在Rails中有一個簡單的任務和評論模型,其中註釋嵌入到任務中。現在任務具有名爲comment_count的屬性。有沒有一種增加計數的方法,以及在一次調用中一起推送新評論。Mongoid - 單呼兩個更新修改更新的MongoDB

任務模式:

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的一種方式,$推$流行等單一更新調用。類似於我們可以在mongo shell中直接進行的操作。

請幫忙。 感謝

回答

1

不幸的是,Mongoid似乎並不支持counter_cache爲ActiveRecord的一樣。

您可以在Comment模型上使用after_saveafter_destroy回調來執行此操作,分別遞增/遞減父級的計數器。

+0

感謝您的答覆。實際上,這次演習的樣子實施counter_cache,但我確實打算是讓使用多個更新修飾符像** $ INC **,** $推**,** $流行**等中的一種方式單一更新呼叫。類似於我們可以在mongo shell中直接進行的操作。我會用這個更新我的問題。 – Dipayan

+1

我不知道mongoid很好,但不是它的[find_and_modify]的目的(http://mongoid.org/en/mongoid/docs/querying.html#find_and_modify)? –