Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render simple JSON array with RABL in Rails

I've been trying to figure out how to make RABL render a very simple JSON array of string, such as: ["my,"array","of","strings"]

The controller would be

class StringsController < ApplicationController
    responds_to :json

    def index
        @string = ['my','array','of','strings']
        respond_with @strings
    end

end

And the RABL view must surely start with:

collection @strings, root_object: false

but I cannot figure out how to just output the strings without a node name or within an object...

There is obviously a much more straightforward solution to actually serving up the JSON array, much like what I've put below, but I'm specifically interested in why this seems so complicated in RABL!

class StringsController < ApplicationController

    def index
        render json: ['my','array','of','strings']
    end

end
like image 807
neill Avatar asked Dec 14 '25 01:12

neill


2 Answers

Neill,

This should work for any arrays, but for your particular array the exact answer is...

In the index.json.rabl use the below code

collection @string, object_root: false

node do |s|
  s 
en

In your controller use...

def index 
    @string = ["my","array","of","strings"]
end
like image 134
Mark Ellul Avatar answered Dec 16 '25 19:12

Mark Ellul


To build on top of Mark's answer, I think it works with this:

collection @string, object_root: false

node :value do |s|
  s 
end

Note I added :value which is the label of the JSON record.

like image 27
netwire Avatar answered Dec 16 '25 19:12

netwire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!