我有哪个地方有许多儿童地方的模型如下所示
class Place < ActiveRecord::Base
belongs_to :parent , class_name: "Place", foreign_key: "parent_id"
has_many :childs , class_name: "Place", foreign_key: "parent_id"
end
我希望以下面的形式从这个模型中获取数据以在树中表示
data = [
{
label: 'place',
children: [
{ label: 'child1' , childern: [ {label: 'child11'} , {label: 'child12'}] },
{ label: 'child2' , childern: [ {label: 'child21'} , {label: 'child22'}] }
]
},
{
label: 'place',
children: [
{ label: 'child3' }
]
}
]
我从这个功能开始
def get_tree(Place)
data = []
Place.all.each do |place|
dataInner= {label: place.name ,id: place.id}
children = [] # to hold childern data
place.childs.each do |child|
childhash = {label: child.name , id: child.id }
children.push(childhash)
end
dataInner.merge!(children: children) # push childern
data.push(dataInner)
end
return data
end
此功能正常但只能获得孩子的深度1。 我希望得到任何深度的孩子的树
答案 0 :(得分:2)
尝试类似
的内容def get_tree(node)
return {label: node.name} if node.childs.empty?
{label: node.name, children: node.childs.collect { |v| get_tree(v) }
end