views:

156

answers:

2

From my Rails 3 app i want a JSON like this: {count:10, pictures:[ {id:1}, ... ] } I tried

render( :json => { :count => 10, :pictures => @pictures.to_json(:only=>:id) } )

but in this case, my pictures get escaped

..."pictures":"[{\"id\":2653299}, ....

In my old merb app i had the following simple line in my controller:

    display( { :count=>@count, :pictures => @pictures } ) 

Because i am using datamapper as my ORM and dm-serializer i am not sure where to influence the generated json.

A: 

Try using the "raw" function. Rails 3 escapes output in the view by default. Try something like this:

raw render( :json => { :count => 10, :pictures => @pictures.to_json(:only=>:id) } )

or it may be possible to escape it inside the render function (although, I have never tried this):

render( :json => { :count => 10, :pictures => raw(@pictures.to_json(:only=>:id)) } )
cowboycoded
Even after some include ActionView::Helpers::RawOutputHelper this does not work, the output will still be escaped.
DeSchleib
A: 

Your code should be:

render( :json => {:count => 10, :pictures => @pictures })

without calling :to_json explicitly on @pictures (the same as it was in your merb app).

However, this will bomb in dm-1.0 without this commit: http://github.com/datamapper/dm-serializer/commit/64464a03b6d8485fbced0a5d7150be90b6dcaf2a

I imagine it will be released soon, but in the meantime it's simple to patch.

edit

I overlooked the fact that you want to use :only => [:id] on your collection. It looks like :as_json has not been implemented on Collections for whatever reason. You can get around this in several ways. Your example might look like this:

render( :json => {:count => 10, :pictures => @pictures.map {|p| p.as_json(:only => [:id])}} )

That will turn your Picture collection into a hash of IDs. render will then do its thang properly and you should get your desired results. (hopefully)

jonuts
I see. So datamapper is responsible to do the serialization, not some fancy ActiveModel-Module. I'll give it a try at the weekend. Thanks.
DeSchleib