Removing child root nodes in RABL
Asked Answered
T

4

24

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"
         }
      ]
   }
]
Tybalt answered 12/3, 2012 at 18:58 Comment(0)
T
48

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
Tombac answered 6/7, 2012 at 19:8 Comment(1)
ive been having this same problem also, and i have tried this solution per the wiki and restarted my server a handful of times, all to no avail.Helluva
V
12

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
Victorious answered 14/3, 2012 at 8:12 Comment(1)
the one above is more perfect :PGrisette
W
2

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?

Whipstock answered 13/3, 2012 at 1:43 Comment(4)
Well, I'm not really trying to adjust it globally. I want to default to including the root nodes.Tybalt
Love this. I would rather tell it to /include/ the object root rather than excluding it.Zolnay
@c00lryguy if you do include_json_root = false, how do you tell it to include the root on a case-by-case basis?Musky
I settled with JSONBuilder so I have no idea, have you tried the selected answer, but flipping the value of root given to the partial?Zolnay
I
0

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
Incarnation answered 22/6, 2014 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.