Rails method to get all descendant categories
Previously, I was shown a concise and excellent way to get all ancestor categories for a given category in a rails application:
def ancestors
result = []
c = self
开发者_JS百科 while c.parent
result.unshift(c.parent)
c = c.parent
end
result
end
Now I'm trying to figure out how to get all of the descendant categories for a given category (children, children of children, etc.) The nearest I've been able to get is the following, but I still have the problem where the final result array is messed up. The top level arrays aren't closed. I've been wrestling with this for hours and am not sure how to fix it.
def descendants
result = []
c = self
for child in c.children
result.push(child)
if(child.children.any?)
result.push(child.descendants)
end
end
result
end
Try this:
def descendants
children.map(&:descendants).flatten
end
def ancestors
[parent, parent.try(:ancestors)].compact.flatten
end
Manual tree traversing has performance implications. You should consider using a gem like ancestry which does a very good job of tree representation.
Edit 1
If you are using the awesome_nested_set
gem, please note that it has ancestors
and descendants
methods on AR instance. You can sort the results of these methods using ruby (If you are dealing with a small set < 100).
category.descendants.sort_by(&:name)
Also acts_as_tree is a great gem by Rails: https://github.com/rails/acts_as_tree
I use it for this very purpose and it automates it all.
精彩评论