简体   繁体   English

Rails 3 respond_to json,带有自定义属性/方法

[英]Rails 3 respond_to json, with custom attributes/methods

In a rails app I have an action that returns a json representation of a collection of different models.在 Rails 应用程序中,我有一个操作返回不同模型集合的 json 表示。 It looks something like this:它看起来这样:

respond_to :json

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

However, I want to customise the attributes and methods that are passed to the json object.但是,我想自定义传递给 json object 的属性和方法。 A bit like:有一点像:

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

Doing the above, causes the json representation of the "cars" to be escaped as one big string, like:执行上述操作会导致“汽车”的 json 表示被转义为一个大字符串,例如:

{
  "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?谁能指出我正确的方向?

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:由于您将to_json嵌套在另一个Hash中,我认为您需要使用as_json (它返回Hash而不是String ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM