0

I have my model 'Person' with Ancestry and I am creating my family tree. In this case, I'm trying to get the first 3 levels of a node, for example:

Starting from the father (1st level), I just want to get all their children (2nd level) and all their grandchildren (3rd level). But I do not want to get their great-grandson (4th level).

Now, if we start with one of the sons (1st level), I want to get your kids (2nd level) and grandchildren of that son (3rd level).

This is the code that I have, but with this obtain all level for a node:

def self.get_tree_json(user)
  json_hash = Hash.new
  if user.has_children?
   array_children = Array.new
   user.children.each do |child| # This function get all children
     array_children << get_tree_json(child)
    end
   json_hash["children"] = array_children
  end
  return json_hash
end
4

1 回答 1

0

您可以启用深度缓存,然后使用 before_depth(?) 或 subtree(to_depth: ?) 选项。从祖先文档:

cache_depth           Cache the depth of each node in the 'ancestry_depth' column (default: false)

before_depth(depth)     Return nodes that are less deep than depth (node.depth < depth)

node.subtree(:to_depth => 2)      Subtree of node, to a depth of node.depth + 2 (self, children and grandchildren)
于 2014-10-22T03:20:56.263 回答