问题描述
在我的Rails 3应用中,我想要这样的JSON:
{count:10,
图片:[
{id:1},
...]}
我尝试过
render(:json => {:count => 10,:pictures => @ pictures.to_json(:only =>:id)})
但在这种情况下,我的图片逃脱
... pictures: [{\ id\:2653299},.. ..
在旧的merb应用程序中,我的控制器中包含以下简单行:
display({:count => @count,:pictures => @pictures})
因为我使用 datamapper
作为我的ORM和 dm-serializer
我不确定在哪里影响生成的json。
您的代码应该是:
render(:json => {:count => 10,:pictures => @pictures})
不调用:to_json exp
但是,如果没有此提交,它将在dm-1.0中轰炸: http://github.com/datamapper/dm-serializer/commit/64464a03b6d8485fbced0a5d7> b 我想它将很快发布,但与此同时它很容易打补丁。 编辑 我忽略了您要在集合中使用:only => [:id]的事实。看起来:as_json出于某种原因尚未在Collections上实现。您可以通过几种方式解决此问题。您的示例可能看起来像这样: 这会将您的图片收藏转换为ID的哈希。然后render将正确地执行它,并且您应该得到想要的结果。 (希望如此) From my Rails 3 app i want a JSON like this: {count:10, pictures:[ {id:1}, ... ] }I tried but in this case, my pictures get escaped In my old merb app I had the following simple line in my controller: Because I am using Your code should be: 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: 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) 这篇关于Rails3:控制生成的JSON(使用datamapper ORM的to_json)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
$ b
render(:json => {:count => 10,:pictures => ; @ pictures.map {| p | p.as_json(:only => [:id])}})
render( :json => { :count => 10, :pictures => @pictures.to_json(:only=>:id) } )
..."pictures":"[{\"id\":2653299}, ....
display( { :count=>@count, :pictures => @pictures } )
datamapper
as my ORM and dm-serializer
I am not sure where to influence the generated json.render( :json => {:count => 10, :pictures => @pictures })
render( :json => {:count => 10, :pictures => @pictures.map {|p| p.as_json(:only => [:id])}} )