格式化 RESTful 数据的正确位置在哪里?
我们越来越多地转向安静的资源,并发现它在数据格式化方面有点痛苦。例如,日期以令人讨厌的完整格式返回,然后需要 JavaScript 或其他代码来进行格式化。
关系要么不包含,要么作为 id 返回,除非您更改 as_json 默认值以包含关系。我最初的想法是通过在表行上复制数据来展平数据,但这对于 has_many 来说效果不佳。
是否有任何文章或播客介绍了解决此问题的“正确”方法?
We are moving more and more to restful resources and have found it a little painful in the data formatting sense. Dates for example come back in nasty full format and then require javascript or other code to do the formatting.
Relationships either aren't included or come back as id's unless you alter the as_json defaults to include the relationships. My initial thought is to flatten the data by duplicating it on the table row but that doesn't work well for has_many.
Are there any articles or podcasts that cover the "right" way to approach this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的表示层应该格式化值以供显示 - 您应该以尽可能最中性的格式存储数据。数据的显示是 UI 关心的问题 - 通过格式化数据,您可以使用多个不同的 UI,这些 UI 可以以不同的方式格式化数据。
Your presentation layer should format values for display - you should store your data in the most neutral format possible. The display of data is a concern of your UI - by formatting the data there you are allowing for multiple different UIs that could format the data different ways.
对我来说,一个好的方法是将渲染的 JSON 数据的格式移动到视图层,使用 rabl宝石。
它允许编写描述 JSON 数据如何呈现的模板,选择要包含的属性和关联,以及其他不错的功能:部分、自定义节点、模板继承等。
A good approach for me was to move the format of rendered JSON data to the view layer, using the rabl gem.
It allows to write templates that describe how your JSON data is rendered, selecting which attributes and associations you want to include, along with nice other functions: partials, custom nodes, template inheritance, etc.