0

I am trying to experiment with mongodb, mongoid and rails. I have a simple Task and Comment model in Rails, where Comments are embedded into Tasks. Now Task has attribute called comment_count. Is there a way of increment the count as well as push a new comment together in a single call.

Task model:

class Task
  include Mongoid::Document
  field :name
  field :desc
  field :comment_count, type: Integer, default: 0
  embeds_many :comments
end

Comment Model:

class Comment
  include Mongoid::Document
  field :entry
  embedded_in :task
end

Below is the operation which I want to do in a single call.

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 

I actually intend to get a way of using multiple update modifiers like $inc, $push, $pop etc in a single update call. Similar to what we can do directly in mongo shell.

Please help. Thanks

Dipayan
  • 113
  • 1
  • 7

1 Answers1

1

Unfortunately, Mongoid does not seem to support counter_cache as ActiveRecord does.

You could use an after_save and an after_destroy callback on your Comment model to implement this, respectively incrementing / decrementing the parent's counter.

m_x
  • 12,357
  • 7
  • 46
  • 60
  • Thanks for the reply. Actually, the current exercise looks like implementing a counter_cache, but what I actually intended was to get a way of using multiple update modifiers like **$inc**, **$push**, **$pop** etc in a single update call. Similar to what we can do directly in mongo shell. I will update my question with this. – Dipayan Nov 10 '12 at 14:31
  • 1
    i don't know mongoid well, but isn't it the purpose of [find_and_modify](http://mongoid.org/en/mongoid/docs/querying.html#find_and_modify) ? – m_x Nov 10 '12 at 16:06