gpt4 book ai didi

ruby-on-rails - Rails 集合到嵌套的 json

转载 作者:行者123 更新时间:2023-12-04 04:39:16 25 4
gpt4 key购买 nike

我需要将 rails 集合转换为嵌套的 json。

收藏:

[
id: 2, name: "Dir 1", parent_id: nil, lft: 1, rgt: 6, depth: 0,
id: 3, name: "Dir 2", parent_id: nil, lft: 7, rgt: 8, depth: 0,
id: 9, name: "Dir 2.1", parent_id: 2, lft: 2, rgt: 3, depth: 1,
id: 10, name: "Dir 2.2", parent_id: 2, lft: 4, rgt: 5, depth: 1
...
]

输出 json

[
{标签:“目录1”, child :[]},
{ 标签:“目录 2”, child :[
标签:“目录 2.1”, child :[],
标签:“Dir 2.2”, child :[]
]}
...
]

最佳答案

这是假设您的收藏与模型相关联并且您正在使用 awesome_nested_set .

class Model

def self.collection_to_json(collection = roots)
collection.inject([]) do |arr, model|
arr << { label: model.name, children: collection_to_json(model.children) }
end
end

end

# usage: Model.collection_to_json

hereroots .

上面的替代方案,因为 awesome_nested_set似乎在 model.children 上产生查询是:
class Model

def self.parents_from_collection
all.select { |k,v| k[:depth] == 0 }
end

def self.children_from_collection(parent)
all.select { |k,v| k[:parent_id] == parent[:id] }
end

def self.collection_to_json(collection = false)
collection ||= parents_from_collection

collection.inject([]) do |arr, row|
children = children_from_collection(row)

arr << { label: row[:name], children: collection_to_json(children) }
end
end
end

关于ruby-on-rails - Rails 集合到嵌套的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com