Rails Tree Structure API [关闭]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rails Tree Structure API [关闭]相关的知识,希望对你有一定的参考价值。
我有JSON:JSON Link
现在我需要创建父子关系。这样我就可以使用数据:
HTTP GET /:tree_id
=> Return the saved structure
HTTP GET /:tree_id/parent/:id
=> Return the list of parents
HTTP GET /:tree_id/child/:id
=> Return the list of childs
我有几个宝石,例如。 acts_as_tree&ancestry但是所有上述宝石都让我使用parent.children来获取数据。
但我需要使用以上API。能否帮助我如何使用关联和模型结构来保存和获取基于上述REST请求的数据。
答案
你怎么样创建一个模块:
module Ancestry
def self.extended(receiver)
receiver.class_eval do
define_method(:children_ids) do |children_ary=[]|
receiver[:child].each_with_object(children_ary) do |child, children_ary|
children_ary << child[:id]
child.extend(Ancestry).children_ids(children_ary)
end if receiver[:child].any?
end
define_method(:parent_ids) do |parents_ary=[]|
if receiver[:child].any?
parents_ary << receiver[:id]
receiver[:child].each_with_object(parents_ary) do |child, parents_ary|
child.extend(Ancestry).parent_ids(parents_ary)
end
end
end
define_method(:node) do |node_id|
return receiver if receiver[:id] == node_id
receiver[:child].each do |child|
child.extend(Ancestry).node(node_id).tap do |x|
return x unless x.blank?
end
end if receiver[:child]
{}.extend(Ancestry)
end
define_method(:child) do
receiver[:child] || []
end
end
end
end
然后像这样扩展你的hash
:
data = {
"id": 1,
"child": [
{
"id": 1847,
"child": [
{
"id": 8078,
"child": []
},
{
"id": 3380,
"child": [
{
"id": 561,
"child": []
},
{
"id": 706,
"child": []
}
]
}
]
}
]
}.with_indifferent_access.extend(Ancestry)
现在你可以这样做:
data.children_ids
=> [1847, 8078, 3380, 561, 706]
data.parent_ids
=> [1, 1847, 3380]
data.node(1847).node(3380).child
=> [{"id"=>561, "child"=>[]}, {"id"=>706, "child"=>[]}]
data.node(9999).node(3380).child
=> []
data.node(1847).node(9999).child
=> []
data.node(1847).node(3380).node(561).child
=> []
以上是关于Rails Tree Structure API [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
[Algorithms] Tree Data Structure in JavaScript
tree-form data structure summary
1159 Structure of a Binary Tree + 根据前序和中序构建二叉树+ 层序遍历模板复习
[数据结构]tree-form data structure summary
在java中把数据库中的Tree Structure转换为JSON对象?
Algorithms - Data Structure - Binary Search Tree - 数据结构之二叉搜索树