【发布时间】:2015-11-09 06:08:18
【问题描述】:
我正在尝试对序列化程序中的关系使用自定义序列化程序并启用 json_api 适配器。但是,关系没有正确序列化(或者,更好的是,根本没有显示/序列化)。
PostController.rb
def index
render json: Post.all, each_serializer: Serializers::PostSerializer
end
序列化器
module Api
module V1
module Serializers
class PostSerializer < ActiveModel::Serializer
attributes :title, :id
belongs_to :author, serializer: UserSerializer
has_many :post_sections, serializer: PostSectionSerializer
end
end
end
end
JSON 输出:
{
"data": [
{
"attributes": {
"title": "Test Title"
},
"id": "1",
"relationships": {
"author": {
"data": {
"id": "1",
"type": "users"
}
},
"post_sections": {
"data": [
{
"id": "1",
"type": "post_sections"
}
]
}
},
"type": "posts"
}
]
}
如您所见,关系未实现,仅当我为关系指定自定义序列化程序时才会发生这种情况!
如果我这样做:
module Api
module V1
module Serializers
class PostSerializer < ActiveModel::Serializer
attributes :title, :id
belongs_to :author # no custom serializer!
has_many :post_sections # no custom serializer!
end
end
end
end
关系显示正确,但未使用自定义序列化程序... 这里有什么问题?
编辑
根据json API 1.0 Format,我得到的是所谓的resource identifier object。
以下主要数据是单个资源标识符对象, 引用相同的资源:
{ “数据”:{ “类型”:“文章”, "id": "1" } }
有没有办法防止获取资源标识符对象,而是获取实际数据?
【问题讨论】:
标签: ruby-on-rails ruby json active-model-serializers