This project is archived and is in readonly mode.

#3812 ✓invalid
Stephen Blackstone

Collection Root for Enumerable to_json

Reported by Stephen Blackstone | January 29th, 2010 @ 10:56 PM

Came across a problem today working with YUI which seems to insist that an array of JSON objects has a defined root which points to the collection

Starting from here:

    render :json => @transactions.to_json(:only => [:id, :scheduled],
                                          :methods => [:amount_total, :overview_status],
                                          :include => {
                                             :actor => { :methods => :display_name },
                                             :fund  => { :only => [:id,:name]      }

I wanted to create { "results" : [ ... regular array of objects ... ] }

One might be tempted to try

render :json => { :results => @transactions.to_jsoin }

...but this fails because render :json will turn it into a string!

You Could do this..

render :json => { :results => @transactions }

... but then you loose the ability to pass filtering options to to_json.

Another solution is to do something like

render :text => "{ "results" : #{@transactions.to_json} }"

....but that makes me want to throw up in my mouth a little.

So I propose that we add a feature to to_json for arrays called :collection_root.

    render :json => @transactions.to_json(:collection_root => "results",
                                          :only => [:id, :scheduled],
                                          :methods => [:amount_total, :overview_status],
                                          :include => {
                                             :actor => { :methods => :display_name },
                                             :fund  => { :only => [:id,:name]      }

Which would then generate:

{ 'results' : [ blah, blah,blah] }

and your json-created objects can then obey your filtering.

Note: Patch is against Rail3 pre and includes test case.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

People watching this ticket