使用额外数据渲染 :json

发布于 2024-10-19 15:44:22 字数 599 浏览 7 评论 0原文

我有一个名为 Todo 的模型,我渲染了这个:

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

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

{
  "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 a model called Todo and I render this:

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自此以后,行同陌路 2024-10-26 15:44:22

要完善布兰登的答案,请尝试使用:

render :json => @todo.attributes.merge({list: { "completion_percentage" => 63 }})

To refine Brandon's answer, try using:

render :json => @todo.attributes.merge({list: { "completion_percentage" => 63 }})
魂归处 2024-10-26 15:44:22

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

format.json { render :json => JSON::parse(@todo.to_json).merge("list" => { "completion_percentage" => 63 }).to_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 }
心房的律动 2024-10-26 15:44:22

正如其他人所知,调用 @todo.attributes 将关闭属性上的自定义方法。例如,如果您的 Todo 模型中有一个方法

    def written_date
      self.written_date = self.written_date.utc.beginning_of_day
    end 

,并且 Todo 模型上有一个名为 write_date 的属性,则只有存储在数据库中的属性才会返回。

并且您希望自定义方法在调用 @todo.attributes 时返回,但事实并非如此。

Just so others are aware, calling @todo.attributes will pull off custom methods on attributes. E.g., if you have in your Todo model a method

    def written_date
      self.written_date = self.written_date.utc.beginning_of_day
    end 

And an attribute called written_date on the Todo Model, only the attribute will come back that is stored in the database.

And you expect the custom method to come back when you call @todo.attributes, it will not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文