So with that said, I'm learning how to do some things with MongoDB & Mongoid that I had run into some trouble with. I'm planning to do a few posts coming up that will be just knowledge dumps and would hopefully be useful to some folks that may be running into the same problems as I did.
One of the things I wanted to do was provide the ability to have threaded comments in the system. Due to the schemaless design of MongoDB, this should be relatively easy. Some of you may have seen this gist then you have encountered the older way to handle this kind of situation where a Comment object would be able to be embedded within a Comment object.
Let's start with a plain Comment Mongoid document class in Ruby.
require 'mongoid' class Comment include Mongoid::Document include Mongoid::Timestamps field :title, type: String field :body, type: String validates_presence_of :body attr_accessible :title, :body endNow, Mongoid 2.0.x now supports recursive models instead of using the syntax seen in the gist. This just requires one line to be added to the class:
recursively_embeds_manyAdding in this will now provide your Comment Mongoid model with two new methods: parent_comment & child_comments. These are dynamically created based on the name of your class (parent_# & child_#s) and they allow you to traverse the hierarchy.
The Comment model would now look something like:
require 'mongoid' class Comment include Mongoid::Document include Mongoid::Timestamps field :title, type: String field :body, type: String #comment.parent_comment # Gets the parent. #comment.child_comments # Gets the children. recursively_embeds_many validates_presence_of :body attr_accessible :title, :body end
That's it! Not so bad once I read the upgrade page that this was changed.