【发布时间】:2018-10-06 16:21:38
【问题描述】:
我在使用 ActiveModelSerializers 正确序列化我的模型时遇到了一些麻烦。设置如下:
# controllers/posts_controller.rb
class PostsController < ApplicationController
def index
render json: @posts, each_serializer: PostSerializer, include: %w(comments), fields: post_fields
end
private
def post_fields
{ posts: [:name, :content, :author] }
end
end
# serializers/post_serializer.rb
class PostSerializer < ActiveModelSerializer
attributes :name, :content, :author
has_many :comments, serializer: CommentSerializer
end
当我向posts#index 端点发出请求时,我期待一个格式为 JSON-API 规范的 JSON 响应,如下所示:
{
"data": {
"type": "post",
"id": 1,
"attributes": {
"name": "My first post",
"author": "Mr. Glass",
"content": "This is my first post ..."
},
"relationships": {
"comments": {
"data": {
"id": 1,
"type": "comments"
}
}
}
},
"included": {
"type": "comments",
"id": 1,
"attributes": {
"content": "First!"
}
}
}
然而,实际的反应是这样的:
{
"data": {
"type": "post",
"id": 1,
"attributes": {
"name": "My first post",
"author": "Mr. Glass",
"content": "This is my first post ..."
}
},
"included": {
"type": "comments",
"id": 1,
"attributes": {
"content": "First!"
}
}
}
整个关系块都不见了。有没有办法让实际响应中的关系块再次出现?
【问题讨论】:
-
您以前有过恋爱关系吗?我在上面的代码中的任何地方都看不到它……它代表什么?您可以将其添加到
include部分吗? -
是的,我做到了。
relationships块应该代表与您在here 中概述的请求的主要资源相关的项目。而且我不这么认为 - 根据 ActiveModelSerializer 文档给出的示例,我不需要指定特定的relationships方法。 -
嗯,我从来没有看过 jsonapi 文档......我也不记得看到过“关系”块从轨道中出来......也许它不是自动做的? (或者我可能是错的......也不是闻所未闻:))
-
你是对的!
relationships不是由 Rails 定义的,而是由active_model_serializergem 定义的,特别是仅在使用json_api适配器选项时(通过各种黑魔法)。 -
酷 - 很抱歉我在这方面缺乏知识......!
标签: ruby-on-rails active-model-serializers json-api