How to use different templates for collection without "root" node with rabl

I've been working with Rabl for a while and just today I ran into an interesting problem that I couldn'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 (no root):

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

      

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

But now I understand that I want to return different templates for each resource based on their attributes .. so easy?

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

      

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

But oh! Now I don't want the "resources" node in there .. how to do that? 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 with no success, it returns empty objects like => [{}, {}, {}]. Any idea how I can do this?

+3


source to share


1 answer


Just remove all "@resources =>: resources" and this should work (assuming it's the content of resources /index.json.rabl and your controllers are setting @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 out https://github.com/rails-api/active_model_serializers as a replacement for rabl. Given your use case, this might be easier to use.

+1


source







All Articles