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