Rails 3使用自定义属性/方法response_to json

时间:2022-12-22 01:21:05

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

在rails应用程序中,我有一个动作,返回不同模型集合的json表示。它看起来像这样:

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. A bit like:

但是,我想自定义传递给json对象的属性和方法。有一点像:

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:

执行上述操作后,会将“cars”的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?

显然我正以错误的方式接近这一点。谁能指出我正确的方向?

1 个解决方案

#1


12  

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
})

#1


12  

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
})