Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Collection Root for Enumerable to_json

#3812

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.

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

State: invalid
Milestone: none
Assigned to: Ryan Bigg Ryan Bigg
Importance: none

Activity

  1. Stephen Blackstone
    Stephen Blackstone

    Please nevermind this patch - this issue is dealt with in 3.0 with the .as_json infrastructure.

    February 9th, 2010 @ 04:33 PM

  2. David Trasbo
    David Trasbo
    • Assigned user set to Ryan Bigg

    April 15th, 2010 @ 10:22 PM

  3. Ryan Bigg
    Ryan Bigg
    • State changed from new to invalid

    Fixed in 3.0.

    April 15th, 2010 @ 10:28 PM