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.