渲染:json和额外的数据 [英] Render :json with extra data

查看:117
本文介绍了渲染:json和额外的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Todo的模型,我对此进行渲染:

I have a model called Todo and I render this:

format.json { render :json => @todo }

每个Todo都属于一个列表.我想将@todo.list.completion_percentage的值添加到JSON,因为我需要它来更新UI(AJAX请求),所以JSON看起来像这样:

Each Todo belongs_to a List. I want to add the value of @todo.list.completion_percentage to the JSON as I need this to update the UI (AJAX request), so the JSON looks something like this:

{
  "todo": {
    "created_at": "2011-02-26T19:39:43Z",
    "updated_at": "2011-02-26T19:53:13Z",
    "done": true,
    "text": "Apples",
    "id": 10,
    "list_id": 2,
    "user_id": 1,
    "due_date": null



    // BELOW THIS LINE SHOULD BE IMPLEMENTED
    "list": {
      "completion_percentage": 63
    }
  }
}

我尝试了各种方法,但是没有任何效果.谁能帮我吗?

I have tried various things but none worked. Can anyone help me?

推荐答案

您可能想要捕获JSON数据的值,然后对其进行修改.

You may want to capture the value of the JSON data, and then modify it.

format.json { render :json => JSON::parse(@todo.to_json).merge("list" => { "completion_percentage" => 63 }).to_json }

这篇关于渲染:json和额外的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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