class Discussion < ActiveRecord::Base belongs_to :post has_many :posts def posts_arranged # arrange(Post.find(:all, :conditions => ["discussion_id = ?", id])) @posts_arranged ||= arrange(Post.find_all_by_discussion_id(id)) end def depth _depth posts_arranged end def _depth(thread) return 0 unless thread.kind_of? Array thread.map { |e| _depth(e) + 1 }.max end private def arrange(posts, root=nil) root ||= posts.find { |post| post.parent.nil? } childs = posts.find_all { |p| p.parent == root.id } [root].concat childs.map { |p| arrange posts, p } end end