RABL: JSON objects without root key
Asked Answered
D

1

6

I have this rabl template:

object @photo
attributes :id
child :comments do
  attributes :id, :body
end

Which gives me this JSON response:

{
  photo: {
    id: 1,
    comments: [
      { 
        comment: {
          id: 1,
          body: 'some comment'
        }
      },
      { 
        comment: {
          id: 2,
          body: 'another comment'
        }
      }
    ]
  }
}

But I want it to look like this:

{
  id: 1,
  comments: [
    { 
      id: 1,
      body: 'some comment'
    },
    { 
      id: 2,
      body: 'another comment'
    }
  ]
}

Why does rabl wrap each element in the array with an extra object called comment. In this way when I access the collection in javascript I have to write:

var comment = image.comments[0].comment

instead of:

var comment = image.comments[0]

I know that if I include :comments in the attributes list for the @photo object it works the way I want, but when I want another level of nested associations for each comment object, there isn't a way to handle that besides using child, but that gives me the JSON response that I don't want.

Maybe I'm just misunderstanding the whole thing -- can someone explain or help? Thanks!

Donatello answered 21/2, 2012 at 23:13 Comment(0)
D
7

Got it!

Create a new file in config/initializers/rabl_config.rb:

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

end
Donatello answered 2/3, 2012 at 21:47 Comment(1)
I had this same problem and found that I needed to add "config.include_child_root = false" in addition to include_json_root = falseCephalo

© 2022 - 2024 — McMap. All rights reserved.