Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RABL: JSON objects without root key

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!

like image 862
Calvin Avatar asked Feb 21 '12 23:02

Calvin


1 Answers

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
like image 58
Calvin Avatar answered Oct 15 '22 02:10

Calvin