2

I have a feed that contains both parent and subclass objects, which i render using RABL into json. I include the root object in the json.

The thing is this => depending on what comes first, the root node in the json will be generated with the corresponding class.

I need it to be all of the parent class.

Example below:

Class Klass
 ...

Class SubclassOfKlass < Klass
 ...

k = Klass.create
s = SubclassOfKlass.create

array1 = [k,s]
Rabl::Renderer.json(nil, 'answers/list', view_path: 'app/views', locals: {object: array1})

## results will render everything as "Klass" objects
## [{\"klass\":{\"_id\":\"1\"},{\"klass\":{\"_id\":\"2\"}]

array2 = [s,k]
Rabl::Renderer.json(nil, 'answers/list', view_path: 'app/views', locals: {object: array1})

## results will render everything as "SubclassOfKlass" objects
## [{\"subclass_of_klass\":{\"_id\":\"1\"},{\"subclass_of_klass\":{\"_id\":\"2\"}]

### But I need the root to be always "klass" and not "subclass_of_klass"

The rabl is as follows (pretty straightforward)

# list.rabl
collection @answers
extends "answers/show"

#show.rabl
if @user
  node(:context_string) { |a| a[:context_string]}
  node(:notebook) do |a|
    if a.class == SubclassOfKlass
      a.notebook
    end
  end
end

extends "klasses/cache"
meow
  • 27,476
  • 33
  • 116
  • 177
  • 1
    Can you post your .rabl template? Also, am I correct in understanding that the JSON generated by RABL looks something like `{"subclass":{...}}` and you would prefer that it look like `{"class":{...}}`? – drewinglis Mar 27 '13 at 01:34
  • @drewinglis done! and yes, you are right. it's pretty puzzling, really – meow Mar 27 '13 at 02:05
  • 1
    @drewinglis thanks for your help - i posted my solution – meow Mar 27 '13 at 16:16

1 Answers1

3

Ok, the answer turns out to be rather straightforward:

collection @answers, :object_root => "answer"
meow
  • 27,476
  • 33
  • 116
  • 177