【问题标题】:Rails 3 respond_to json, with custom attributes/methodsRails 3 respond_to json,带有自定义属性/方法
【发布时间】:2011-09-24 11:34:21
【问题描述】:

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

respond_to :json

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

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

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

执行上述操作会导致“汽车”的 json 表示被转义为一个大字符串,例如:

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

显然,我以错误的方式处理这个问题。谁能指出我正确的方向?

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-3 activerecord


    【解决方案1】:

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

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

    【讨论】:

    • 看准了!谢谢你。 (我会尽快接受这个答案)
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2012-10-20
    • 2013-10-19
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多