返回基于 id 的扩展记录,作为 JSON 结果的一部分
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
抱歉回复很简洁,但是
to_json
和:include
就差不多了。我刚才还没有在控制器中测试过它,但在控制台上试了一下,结果还不错。Try:
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.