2012-11-10 8 views
0

mongodb, mongoid 및 rails을 실험하려고합니다. 코멘트가 작업에 포함되는 간단한 Task and Comment 모델이 레일즈에 있습니다. 이제 Task에는 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 같은 여러 업데이트 수정을 사용하는 방법을 얻을 계획입니다. 우리가 몽고 껍질에서 직접 할 수있는 것과 비슷합니다.

도와주세요. 감사합니다.

답변

1

불행히도 Mongoid는 ActiveRecord처럼 counter_cache을 지원하지 않는 것 같습니다.

Comment 모델에서 after_saveafter_destroy 콜백을 사용하여이 기능을 구현할 수 있으며, 부모 카운터를 각각 증가/감소시킵니다.

+0

답장을 보내 주셔서 감사합니다. 실제로, 현재 운동은 counter_cache를 구현하는 것처럼 보이지만 실제로 의도 한 것은 ** $ inc **, ** $ push **, ** $ pop ** 등의 여러 가지 수정 수정자를 사용하는 방법을 얻는 것이 었습니다. 단일 업데이트 호출. 우리가 몽고 껍질에서 직접 할 수있는 것과 비슷합니다. 나는 내 질문을 이것으로 업데이트 할 것이다. – Dipayan

+1

나는 몽고이드를 잘 모릅니다. 그러나 [find_and_modify] (http://mongoid.org/en/mongoid/docs/querying.html#find_and_modify)의 목적이 아닙니까? –

관련 문제