【问题标题】:JSON - Nesting children RABL or JBuilder for RailsJSON - 嵌套子 RABL 或 JBuilder for Rails
【发布时间】:2013-10-18 19:00:14
【问题描述】:

我的对象看起来像:

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

ltree_val 决定它们的树结构。

我需要生成类似...

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

我的孩子由 ltree 值确定,它们本身就是同一对象的元素。

如果我按它们的 ltree 值对这些对象进行排序,我如何创建嵌套条目?

我愿意接受 RABL 或 JBuilder。我完全迷路了。

【问题讨论】:

    标签: ruby-on-rails ruby json rabl jbuilder


    【解决方案1】:

    答案是使用递归函数...

    # 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
    

    这构建了类似的东西

    [
      {  "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"
            }
          }
        ]
      }
    ]
    

    【讨论】:

    • 递归函数应该驻留在哪个文件中?它是控制器、部分还是助手?
    • json 参数对我不起作用。它报告错误数量的参数(1 对 2)。你得到这个工作了吗?
    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2014-10-21
    • 2014-10-01
    相关资源
    最近更新 更多