轨道3的respond_to JSON,具有自定义属性/方法 [英] Rails 3 respond_to json, with custom attributes/methods

查看:171
本文介绍了轨道3的respond_to JSON,具有自定义属性/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Rails应用程序我有一个返回不同型号的集合的JSON重新presentation一个动作。它看起来的的东西的是这样的:

In a rails app I have an action that returns a json representation of a collection of different models. It looks something like this:

respond_to :json

def index
  @cars = Car.all
  @vans = Van.all
  respond_with({
    :cars => @cars,
    :vans => @vans
  })
end

不过,我想自定义传递给JSON对象的属性和方法。好像有点:

However, I want to customise the attributes and methods that are passed to the json object. A bit like:

respond_with({
  :cars => @cars.to_json(:only => [:make, :model], :methods => [:full_name]),
  :vans => @vans
})

做好以上,导致的车被转义为一个大的字符串的JSON重新presentation,如:

Doing the above, causes the json representation of the "cars" to be escaped as one big string, like:

{
  "cars":"[{\"car\":{\"make\":\"Ford\"  ... etc
  "vans": [{"van":{"make":"Citreon"  ... vans not escaped
}

很显然,我这接近了错误的方式。任何人都可以点我朝着正确的方向?

Obviously I'm approaching this the wrong way. Can anyone point me in the right direction?

推荐答案

既然你嵌套 to_json 在另一散列,我认为你需要使用 as_json (返回散列,而不是字符串)代替:

Since you're nesting the to_json in another Hash, I think you need to use as_json (which returns a Hash instead of a String) instead:

respond_with({
  :cars => @cars.as_json(:only => [:make, :model], :methods => [:full_name]),
  :vans => @vans
})

这篇关于轨道3的respond_to JSON,具有自定义属性/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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