使用额外数据渲染 :json
我有一个名为 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要完善布兰登的答案,请尝试使用:
To refine Brandon's answer, try using:
您可能想要捕获 JSON 数据的值,然后对其进行修改。
You may want to capture the value of the JSON data, and then modify it.
正如其他人所知,调用 @todo.attributes 将关闭属性上的自定义方法。例如,如果您的 Todo 模型中有一个方法
,并且 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
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.