简体   繁体   中英

Rails collection to nested json

I need to convert rails collection to nested json.

Collection:

[
       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 
       ...
    ]

output json

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

This is assuming your collection is tied to a model and you're using 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

See here for roots .

An alternative to the above, because awesome_nested_set appears to produce queries on model.children is:

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

尝试to_json方法

collection.to_json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM