Rails3:控制生成的JSON(使用datamapper ORM的to_json) [英] Rails3: Take control over generated JSON (to_json with datamapper ORM)

查看:78
本文介绍了Rails3:控制生成的JSON(使用datamapper ORM的to_json)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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
$ b

我想它将很快发布,但与此同时它很容易打补丁。



编辑



我忽略了您要在集合中使用:only => [:id]的事实。看起来:as_json出于某种原因尚未在Collections上实现。您可以通过几种方式解决此问题。您的示例可能看起来像这样:

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

这会将您的图片收藏转换为ID的哈希。然后render将正确地执行它,并且您应该得到想要的结果。 (希望如此)


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.

解决方案

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)

这篇关于Rails3:控制生成的JSON(使用datamapper ORM的to_json)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆