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

标签 ruby-on-rails json collections nested

我需要将 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


    [
        { label: "Dir 1", children:[] },
        { label: "Dir 2", children: [
            label: "Dir 2.1", children: [],
            label: "Dir 2.2", children: []
        ]}
        ...
    ]

最佳答案

这是假设您的收藏与模型绑定(bind)并且您正在使用 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

参见here对于

上述方案的替代方案是:

,因为 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/

相关文章:

ruby-on-rails - ruby 中 Redis 对象上的 Redis 对象列表

javascript - 如何在多级未定义键中设置键值对

javascript - 访问 .json 文件中的字段

java - 将 JSON 转换为 map

java - 使用哪个集合?

java - 如何迭代 TreeMap 直到特定键?

ruby-on-rails - 如何验证字符串的第一个字符不是整数?

ruby-on-rails - 转储 Heroku 数据库以在本地 seed.rb 中使用的最简单方法?

ruby-on-rails - 我运行命令 "rake test"并收到此错误

ios - Watson iOS SDK (Swift) 并将上下文变量传递给 Conversation