Database Reference
In-Depth Information
Home
Outdoors
Gardening
Tools
Seedlings
Planters
Lawn care
Figure 6.2
Adding a Gardening category
Figure 6.2 displays the updated tree.
That's easy enough. But what if you now want to place the Outdoors category
underneath Gardening? This is potentially complicated because it alters the ancestor
lists of a number of categories. You can start by changing the parent_id of Outdoors
to the _id of Gardening. This turns out to be not too difficult:
@categories.update({:_id => outdoors_id},
{'$set' => {:parent_id => gardening_id}})
Since you've effectively moved the Outdoors category, all the descendants of Out-
doors are going to have invalid ancestor lists. You can rectify this by querying for all
categories with Outdoors in their ancestor lists and then regenerating those lists.
MongoDB's power to query into arrays makes this trivial:
@categories.find({'ancestors.id' => outdoors_id}).each do |category|
generate_ancestors(category['_id'], outdoors_id)
end
That's how you handle an update to a category's parent_id attribute, and you can see
the resulting category arrangement in figure 6.3.
Home
Gardening
Outdoors
Tools
Seedlings
Planters
Lawn care
Figure 6.3 The category tree
in its final state
Search WWH ::




Custom Search