返回基于 id 的扩展记录,作为 JSON 结果的一部分

发布于 2024-11-01 20:31:42 字数 762 浏览 0 评论 0原文

我有一个 Rails 服务器将数据以 JSON 形式返回到我的移动应用程序,如下所示,

在控制器中,

format.json { 渲染 :json =>; @游戏 }

返回,

{"game":{"created_at":"2011年4月14日星期四 11:14","title":"扔香蕉","updated_at":"2011年4月14日星期四11:16","id":5 ,"day":"2011-07-14","location_id":5}}

返回的记录包括从“game”表到另一个表“location”的引用,特别是该表中 id 为 5 的条目。

现在,我的移动应用程序可以跳过一些环节来解析另一个表中的 location_id,但如果最初返回的 JSON 已经解析了 location_id 值并包含扩展的“位置”,那么它会更加直接记录在原始结果中,例如

{"game":{"created_at":"2011年4月14日星期四 11:14","title":"扔香蕉","updated_at":"2011年4月14日星期四11:16","id":5 ,"day":"2011-07-14","location":{"place":"白金汉宫"}}}

...其中位置表中 id 为 5 的条目已扩展为嵌套 JSON。

是否可以在服务器端执行此操作,如果可以,如何执行?

任何对此的帮助将不胜感激。

谢谢。

I have a Rails server returning data to my mobile App as JSON, as follows,

In controller,


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

Which returns,


{"game":{"created_at":"Thu, 14 Apr 2011 11:14","title":"Banana throwing","updated_at":"Thu, 14 Apr 2011 11:16","id":5,"day":"2011-07-14","location_id":5}}

The returned record includes a reference from the 'game' table to another table, 'location', and specifically the entry with the id of 5 in that table.

Now, my mobile App could jump through some hoops to resolve that location_id in the other table, but it would be a whole lot more straight-forward if the JSON that is initially returned had already resolved the location_id value and included the expanded 'location' record in the original result, something like,


{"game":{"created_at":"Thu, 14 Apr 2011 11:14","title":"Banana throwing","updated_at":"Thu, 14 Apr 2011 11:16","id":5,"day":"2011-07-14","location":{"place":"Buckingham Palace"}}}

...where entry with id of 5 in the location table has been expanded as nested JSON.

Is it possible to do this on the server side, and if so how?

Any help with this would be very much appreciated.

Thank you.

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

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

发布评论

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

评论(1

待天淡蓝洁白时 2024-11-08 20:31:42

尝试:

format.json { render :json => @person.to_json(:include => [:location]) }

抱歉回复很简洁,但是 to_json:include 就差不多了。我刚才还没有在控制器中测试过它,但在控制台上试了一下,结果还不错。

Try:

format.json { render :json => @person.to_json(:include => [:location]) }

Sorry for the terse response, but to_json with :include is pretty much it. I have not tested it in the controller just now but gave it a go at the console and it was OK.

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