【问题标题】:How to create custom "containing" JSON in RABL?如何在 RABL 中创建自定义“包含”JSON?
【发布时间】:2014-11-17 04:16:22
【问题描述】:

我正在编写具有两种端点类型的 API:单一端点和聚合端点。我有单个端点的 RABL 视图,如下:

# cat_view.json.rabl
object @cat
attributes :name

# dog_view.json.rabl
object @dog
attributes :name

这些按预期工作,但是我在聚合 RABL 视图中苦苦挣扎。我想要的 JSON 结构是:

{
  'cats': {
    'details': [{'name': 'Mittens'},
                {'name': 'Mr. Wiskers'},
                {'name': 'Crookshanks'}],
    'count' : 3
  },
  'dogs': {
    'details': [{'name': 'Rover'},
                {'name': 'Fido'}],
    'count' : 2
  }
}

我当前的聚合 RABL 视图是:

# animals.json.rabl
child @cats do
  collection @cats, :object_root => false
  extends "cat_view"
end
node(:cat_count) { @cats.count }

child @dogs do
  collection @dogs, :object_root => false
  extends "dog_view"
end
node(:dog_count) { @dogs.count }

这会产生这个 JSON:

    {'cats': [{'name': Mittens'},
              {'name': Mr. Wiskers'},
              {'name': Crookshanks'}],
    'cat_count': 3,
    'dogs': [{'name': 'Rover'},
             {'name': 'Fido'}],
    'dog_count': 2}

我的问题:

我的animals.json.rabl 应该如何查看才能获得上述 JSON 结构?

【问题讨论】:

    标签: ruby-on-rails json rabl


    【解决方案1】:

    要添加details 键,请将现有的child @cats 块命名为details

     child @cats => :details do
       collection @cats, :object_root => false
       extends "cat_view"
       node(:count) { @cats.count }
     end
    

    对于问题的嵌套部分,您可以通过创建一个新的包装子块来做到这一点:

    # animals.json.rabl
    child :cats do
     child @cats => :details do
       collection @cats, :object_root => false
       extends "cat_view"
       node(:count) { @cats.count }
     end
    end
    
    child :dogs do
     child @dogs => :details do
       collection @dogs, :object_root => false
       extends "dog_view"
       node(:count) { @dogs.count }
     end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2023-04-06
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多