A Nested Comments Example
... a nested set tree implementation in the ORM from Rails.Would a nested comments implementation be adequate?
Here is the DB Schema:
create table comments (\n id int not null auto_increment,\n content text not null,\n parent_id int,\n updated_on date,\n primary key(id)\n )
Here is the ActiveRecord model object
class Comment < ActiveRecord::Base\n acts_as_tree :order=>"updated_on"\n\n def nested_display(level=0)\n print " " * level\n puts "#{content} (#{updated_on})"\n children.each do |child| child.nested_display(level + 1) end\n end\nend
Here is a script to populate a few comments:
require 'active_record'\nrequire 'comments'\n\nActiveRecord::Base.establish_connection(\n :adapter => "mysql",\n :database => "comments_development",\n :socket => "/var/run/mysqld/mysqld.sock",\n :username => "jim"\n)\n\nroot_comment = Comment.create(:content => "This is great!")\ndisagree = Comment.create(:content => "No it isn't.", :parent => root_comment)\nargue = Comment.create(:content => "You're nuts.", :parent => disagree)\nagree = Comment.create(:content => "Right on Brother.", :parent => root_comment)
And here is a script to dump the comments (I'll omit the connection code this time, which is the same as the populate script above).
# [... connection code elided ...]\nComment.roots.each do |comment| comment.nested_display end
And finally, the output of the dump script against a real database.
$ ruby dump.rb\nThis is great! (2005-11-29)\n No it isn't. (2005-11-29)\n You're nuts. (2005-11-29)\n Right on Brother. (2005-11-29)