我有一个自我参照模型,
class Hierarchy < ActiveRecord::Base
has_many :children, :class_name => "Hierarchy", :foreign_key => 'parent_id'
def descendents
children.map do |child|
[child] + child.descendents
end
end
end
如何从Model&#34; Hierarchy&#34;中构建一个层次结构树。像这样,
{
"hierarchies": [
{
"level": 1, "id": 14951, "name": "EQUIPMENT", "parent_id": null,
"children": [
{
"level": 2, "id": 15040, "name": "BASKETBALL", "parent_id": 14951,
"children": [
{
"level": 3, "id": 15154, "name": "EYEWEAR", "parent_id": 15040,
"children": [
{
"level": 4, "id": 16617, "name": "OPHTHALMIC", "parent_id": 15154,
"children": []
}
]
},
{
"level": 3, "id": 16417, "name": "OTHER", "parent_id": 15040, "children": []
}
]
}
]
}
]
}
&#34; Herarchy&#34;模型的descendents
方法可以迭代并从Herarchy模型中检索数据直到最后一级。
示例:
render :json => { :hierarchies => [root_hierarchy, root_hierarchy.descendents]}
它返回所有级别,
{
"hierarchies": [
{
"level": 1, "id": 14951, "name": "EQUIPMENT", "parent_id": null
},
[
[
{
"level": 2, "id": 15040, "name": "BASKETBALL", "parent_id": 14951
},
[
{
"level": 3, "id": 15154, "name": "EYEWEAR", "parent_id": 15040
},
[
{
"level": 4, "id": 16617, "name": "OPHTHALMIC", "parent_id": 15154
}
]
],
[
{
"level": 3, "id": 16417, "name": "OTHER", "parent_id": 15040
}
]
]
]
]
}
问题是我无法在每次迭代中附加其关联的子项。
我尝试使用as_json
,includes
方法将子项追加到其父对象中,但没有运气。
答案 0 :(得分:0)
之前我遇到过同样的问题。我建议你看一下closure_tree。它为操作分层数据添加了一些非常有用的方法。它有一种抓取后代的方法,只需要1个SELECT查询。您使用邻接列表的当前实现很简单,但每个后代需要一个查询,并且很快就会变得低效。