3

I'm working with Rabl for a while and just today I faced an interesting problem that I could't solve quite well..

So, I have a collection returned from GET ".../list/512/resources" and here is my sample rabl template that I used to return (without root) :

collection @resources
extends "api/v1/resources/_base"

=> { [ {...}, {...}, {...} ] }

But, now I realize that I want to return different templates for each resource depending on their attributes.. so that's easy right?

node @resources => :resources do |resource|
  if resource.type == 'Document'
    partial('...', :object => resource)
  elsif @resource.type == 'Folder'
    partial('...', :object => resource)
  end
end

=> { resources: [ {...}, {...}, {...} ] }

But ohh! Now I don't want that "resources" node there.. how should it be done? I tried something like:

array = []

@resources.each do |resource|
  if resource.type == 'Document'
    array << partial('...', :object => resource)
  elsif @resource.type == 'Folder'
    array << partial('...', :object => resource)
  end
end

collection array

but no success, it returns empty objects like => [ {}, {}, {} ]. Any idea how can I accomplish that?

mateusmaso
  • 7,843
  • 6
  • 41
  • 54

1 Answers1

1

Just remove the whole "@resources => :resources" and that should work (provided this is the content of resources/index.json.rabl and your controller sets @resources)

node do |resource|
  if resource.type == 'Document'
    partial('...', :object => resource)
  elsif @resource.type == 'Folder'
    partial('...', :object => resource)
  end
end

You might want to check https://github.com/rails-api/active_model_serializers as a replacement for rabl. Given your use case it might be easier to use.

Arnaud
  • 17,268
  • 9
  • 65
  • 83
  • yeah, active model serializers rules! I've been using it since created that question and got frustrated with rabl – mateusmaso Mar 29 '13 at 04:06