In a tree-based model, you have some tradeoffs if you want to retrieve
multiple values efficiently. Usually this is an insert-time vs query-
time tradeoff. For example, if you wanted to keep track of the number
of descendants of any particular node, you would either have to
traverse the node's subtree to count all the children every time you
wanted that information, or whenever you insert a child, you add one
to the parent's descendant-count field, then the grandparent's, and so
on, eventually bubbling this information up to the root. This way
every node is guaranteed to have an up-to-date count.

Your situation is similar. You can add a descendants field containing
an array of descendant IDs. Using the built-in activerecord
serialization mechanism:

class Person < ActiveRecord::Base
  serialize :descendants
  ...
end

Every time you create a new Person, all you need to do is

  descendants = new_person.parent.descendants
  descendants << new_person.parent.id

Of course, this will be a bit more complex if you want to include
dependants from multiple parents, but the idea is the same. Now every
person includes a list of descendant IDs, and you'll need only a
single query.

-- Mark.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to