Rails 3 respond_to json, with custom attributes/methods

家住魔仙堡 提交于 2019-12-22 04:58:06

问题


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

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/6509736/rails-3-respond-to-json-with-custom-attributes-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!