Mongoid: Run callback from embedded document on parent
Rails 3.0.1 Mongoid (2.0.0.beta.20)
Class Post embeds_many :comments field :comments_count end
Class 开发者_StackOverflowComment
embedded_in :commentable, :inverse_of => :comments
end
I want to select the 10 most commented posts. To do that I need comments_count field in Post. But since my Comment is polymorphic (Post.comments, Message.comments etc) I don't want create inc callbacks in Post. What I wan't to do is create callback in Comment which will update comment_count field in Post.
I don't know how I can perform inc operation in embedded document on Field from parrent document and execute this callback from parrent document
Here is how to increment the Post
from the embedded 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 pretty sure that this callback will execute whenever a new Comment is created so I don't think you need to worry about executing it from the parent document. Let me know if it works.
See this SO answer and this Github issue for more info on callbacks in embedded documents.
精彩评论