3

I have objects that look like:

[<ltree_val: "1", contents: "blah">, 
 <ltree_val: "1.1", contents: "blah">,
 <ltree_val: "1.1.1", contents: "blah">,
 <ltree_val: "2", contents: "blah">,
 <ltree_val: "2.1", contents: "blah">]

Where ltree_val determines their tree structure.

I need to generate something like...

[{ "data" : "1",
  "children" : 
      [{ "data" : "1.1",
         "children" : 
              [{ "data" : "1.1.1" }]
       }]
  },
  { "data" : "2" }]

Where I have children which are determined by an ltree value, which are themselves elements of the same object.

If I sort these objects by their ltree value, how can I create nested entries?

I'm open to either RABL or JBuilder. I'm totally lost.

robbiep
  • 113
  • 1
  • 10

1 Answers1

5

The answer was to use a recursive function...

# encoding: UTF-8

def json_ltree_builder( json, ltree_item )
  json.title t( ltree_item.title )
  json.attr do
    json.id ltree_item.id
  end
  json.metadata do
      json.val1 ltree_item.val1
      json.val2 ltree_item.val2
    end
  children = ltree_item.children
  unless children.empty?
    json.children do
      json.array! children do |child|
        json_ltree_builder( json, child )
      end
    end
  end
end

json.array! @menu_items do |menu_item|
  json_ltree_builder( json, menu_item )
end

This builds something like

[
  {  "title":"Title 1", 
    "attr" : {
      "id": 111
    },
    "data" : {
      "val1" : "Value 1",
      "val2" : "Value 2"
    },
    "children" : [
      {
        "title":"Child 1", 
        "attr" : {
          "id": 112
        },
        "data" : {
          "val1" : "Value 1",
          "val2" : "Value 2"
        }
      },
      {
        "title":"Child 2", 
        "attr" : {
          "id": 112
        },
        "data" : {
          "val1" : "Value 1",
          "val2" : "Value 2"
        }
      }
    ]
  }
]
robbiep
  • 113
  • 1
  • 10
  • 1
    Which file should the recursive function reside in? Is it the controller, a partial or a helper? – MSC Dec 01 '14 at 13:07
  • The json argument does not work for me. It reports wrong number of arguments (1 for 2). Did you get this to work? – Khanetor Mar 17 '15 at 10:56