Mongoid: execute callback from inline document to parent

Rails 3.0.1 Mongoid (2.0.0.20)

Class message embes_many: comments Field: comments_count end

Class Comment embedded_in :commentable, :inverse_of => :comments end 

I want to select the 10 most commented posts. To do this, I need the comment_count field in Post. But since my comment is polymorphic (Post.comments, Message.comments, etc.), I do not want to create callbacks in Post. What I will not do is create a callback in the comment that will update the comment_count field in Post.

I do not know how I can perform an operation in an embedded document in a field from a source document and execute this callback from a parrent document

+4
source share
1 answer

Here's how to increase Post from the built-in polymorphic Comment :

 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 

I am sure that this callback will be executed whenever a new comment is created, so I don’t think you need to worry about its execution from the parent document. Let me know if this works.

See this SO> answer and this Github question for more information on callbacks in embedded documents.

+6
source

All Articles