问题
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.
回答1:
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)
回答2:
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)) } )
来源:https://stackoverflow.com/questions/3742283/rails3-take-control-over-generated-json-to-json-with-datamapper-orm