2
class Node < ActiveRecord::Base
  attr_accessible :name

  belongs_to :parent_node, :class_name => "Node", :foreign_key => :parent_id
  has_many :child_nodes, :class_name => "Node", :foreign_key => :parent_id
end

For the root node, parent_id will be nill. Say I have the id of the root node, and wish to print the entire tree to the output stream in json format.

How do I go about doing that?

Assume the tree does not contain any loops.

The Trav
  • 1,955
  • 3
  • 22
  • 30
  • Check this question http://stackoverflow.com/questions/9944005/how-to-generate-json-tree-from-ancestry – dimuch Jun 09 '12 at 06:55

1 Answers1

1

Sounds like you need awesome_nested_set. The wiki is well documented but can be hard to find if you don't know it's there.

In your case, you'll want to do something like:

Node.root.self_and_descendants
Zubin
  • 9,422
  • 7
  • 48
  • 52