Database Reference
In-Depth Information
a list of its ancestors. The one tricky requirement is keeping all the ancestor lists up to
date. Let's look at an example to see how this is done.
What you need first is a generic method for updating the ancestor list for any given
category. Here's one possible solution:
def generate_ancestors(_id, parent_id)
ancestor_list = []
while parent = @categories.find_one(:_id => parent_id) do
ancestor_list.unshift(parent)
parent_id = parent['parent_id']
end
@categories.update({:_id => _id},
{"$set" {:ancestors => ancestor_list}})
end
This method works by walking backward up the category hierarchy, making successive
queries to each node's parent_id attribute until reaching the root node (where
parent_id is nil ). All the while, it builds an in-order list of ancestors, storing that
result in the ancestor_list array. Finally, it updates the category's ancestors attri-
bute using $set .
Now that you have that basic building block, let's look at the process of inserting a
new category. Imagine you have a simple category hierarchy that looks like the one
you see in figure 6.1.
Suppose you want to add a new category called Gardening and place it under the
Home category. You insert the new category document and then run your method to
generate its ancestors:
category = {
:parent_id => parent_id,
:slug => "gardening",
:name => "Gardening",
:description => "All gardening implements, tools, seeds, and soil."
}
gardening_id = @categories.insert(category)
generate_ancestors(gardening_id, parent_id)
Home
Outdoors
Tools
Seedlings
Planters
Lawn care
Figure 6.1
An initial category hierarchy
Search WWH ::




Custom Search