使用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!"
}
}
}
整个关系块都缺失了。有没有办法让实际响应中的关系块再次出现?
答案 0 :(得分:1)
我明白了!
对于任何未来的读者 - 如果您希望ActiveModelSerializers中存在relationships
块以及使用fields
选项,则需要执行以下操作:
# in your controller
render json: @posts, include: %(comments), fields: post_fields
def post_fields
# note the inclusion of "comments" in the array of fields to be
# serialized. That is the change you will need to make.
{ posts: [:name, :author, :content, :comments] }
end
希望有所帮助!