Created
August 2, 2010 13:47
-
-
Save JonKernPA/504671 to your computer and use it in GitHub Desktop.
Nested comments on a Blog using MongoMapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Be sure to have mongod running | |
# Below is an attempt to show one way to have nested comments on a blog post | |
# I did not thoroughly examine whether it is bulletproof or performant. | |
# But it seems to work :-) | |
col = Blog.all() | |
col.each {|c| c.destroy } | |
col = Comment.all() | |
col.each {|c| c.destroy } | |
class Blog | |
include MongoMapper::Document | |
key :title, String | |
many :comments | |
def to_s | |
puts "\n----------\n#{title}" | |
comments.each do |c| | |
c.to_s if c.comment_id.nil? | |
end | |
end | |
end | |
class Comment | |
include MongoMapper::Document | |
key :text, String | |
many :comments | |
key :comment_id, ObjectId | |
belongs_to :comment | |
key :blog_id, ObjectId | |
belongs_to :blog | |
def to_s(depth = 1) | |
prefix = "\t"*depth | |
puts "#{prefix}#{text}" | |
comments.each do |c| | |
c.to_s(depth+1) | |
end | |
end | |
end | |
blog = Blog.create(:title => "Greatest Idea Ever" ) | |
c1 = Comment.create( :text => "Comment 1", :blog => blog) | |
c2 = Comment.create(:text => "Comment 2", :blog => blog) | |
c11 = Comment.create(:text => "Comment 1 - 1", :blog => blog, :comment => c1) | |
c12 = Comment.create(:text => "Comment 1 - 2", :blog => blog, :comment => c11) | |
blog.to_s | |
# OUTPUT: | |
# ---------- | |
# Greatest Idea Ever | |
# Comment 1 | |
# Comment 1 - 1 | |
# Comment 1 - 2 | |
# Comment 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment