Removing child root nodes in RABL

人走茶凉 提交于 2019-11-29 05:27:42

问题


I'm trying to render a pretty simple data structure using RABL, but I can't figure out how to remove the child root nodes properly. Here are my two templates.

First, the collection index template.

collection @groups, :object_root => false

attributes :id, :name
child :files do
  extends 'groups/_file'
end

And next, the file partial template.

object @file

attributes :id

Those two templates end up producing the following JSON:

[
   {
      "id":"4f57bf67f85544e620000001",
      "name":"Some Group",
      "files":[
         {
            "file":{
               "id":"4f5aa3fef855441009000007"
            }
         }
      ]
   }
]

I want to find a way to remove the root "file" key inside of the files collection. Something like:

[
   {
      "id":"4f57bf67f85544e620000001",
      "name":"Some Group",
      "files":[
         {
            "id":"4f5aa3fef855441009000007"
         }
      ]
   }
]

回答1:


On latest versions of Rabl, you have to set this configuration if you want include_root_json to be false in all levels.

Rabl.configure do |config|
  config.include_json_root = false
  config.include_child_root = false
end



回答2:


Try replacing:

    child :files do
      extends 'groups/_file'
    end

with:

    node :files do |group|
      group.files.map do |file|
        partial 'groups/_file', object: file, root: false
      end
    end



回答3:


This is the usual way of removing the root json (rather than specifying object_root: false)

config/initializers/rabl_config.rb

Rabl.configure do |config|
  config.include_json_root = false
end

Does moving that to there (and restarting rails), fix it?




回答4:


just putting it out there, in case you want to apply it for a specific child:

child :files, :object_root => false do
  extends 'groups/_file'
end


来源:https://stackoverflow.com/questions/9673136/removing-child-root-nodes-in-rabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!