【发布时间】:2017-01-31 15:12:05
【问题描述】:
考虑以下两个实体:帖子、作者
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, author_id
belongs_to :author
end
Class AuthorSerializer < ActiveModel::Serializer
attributes :id, :name
end
使用 'JSON' 适配器,对于 PostsController 的索引操作,我们得到如下响应:
{
"posts":[
{
"id":1,
"title":"Hic consectetur et delectus",
"author_id": 1,
"author":{"id":1,"name":"Author-A"}
},
{
"id":2,
"title":"Hic consectetur et delectus",
"author_id": 2,
"author":{"id":2,"name":"Author-B"}
},
{
"id":3,
"title":"Hic consectetur et delectus",
"author_id": 1,
"author":{"id":1,"name":"Author-A"}
}
]
}
是否可以将文章数据之外的作者数据分组以进行侧载? (如下图)
{
posts:[{...}, {...}, {...}],
authors:[
{id:1, name:'Author-A'},
{id:2, name:'Author-B'}
]
}
【问题讨论】:
-
这很有可能,但是你会失去关系..这样做有什么意义..它与单独拥有两个 ActiveRecord 对象一样好。
-
系统中有几个组件需要上述格式的数据。这在 AMS 0.8.x 中使用嵌入 :ids 是可能的,但在 AMS 0.10.x 中找不到等效项
-
0.8可以认为是jsonapi的早期草稿。嵌入已包含在内。
-
@BF4 我假设您指的是关联选项中的“包含:”。否则请更正.. 这不会修改 json 格式。 (使用 json 适配器时)
-
@Pratheeswaran.R 好吧,有一个包含查询参数和一个包含的 json 根。无论如何,当我说嵌入被包含时,我并不是指代码。我的意思是 JSON:API 在达到 1.0 之前已经开发了一段时间,嵌入是包含的前身,而 AMS 是很多早期的 JSON:API 已经实现。如果我没有解决正确的问题,我深表歉意。我打算回答为什么 0.10 缺少 embed
标签: ruby-on-rails-5 active-model-serializers