我有一个作者,他有很多书,还有一本属于 Rails 7 api 中某个作者的书。我正在使用 "jsonapi-serializer", "~> 2.2" 尝试获取作者及其书籍。当我查看 json 文件时,我得到这个:
{
"id": "1",
"type": "author",
"attributes": {
"id": 1,
"fname": "John",
"lname": "Doe"
},
"relationships": {
"books": {
"data": [
{
"id": "1",
"type": "books"
},
{
"id": "2",
"type": "books"
},
{
"id": "3",
"type": "books"
},
{
"id": "4",
"type": "books"
},
{
"id": "5",
"type": "books"
}
]
}
}
}
我想扩展关系中的内容以显示完整信息或至少对其进行自定义,以便它显示 id、名称、release_year 等内容,而不仅仅是 id 和类型。我不想再进行一次数据库查询来获取书籍。
AuthorSerializer 看起来像这样:
class AuthorSerializer
include JSONAPI::Serializer
attributes :id, :fname, :lname
has_many :books
end
BookSerializer 看起来像这样:
class BooksSerializer
include JSONAPI::Serializer
attributes :id, :name, :release_year, :awards, :genre, :price, :blurb, :isbn
belongs_to :author
end
作者控制器如下所示:
class AuthorController < ApplicationController
before_action :set_author, only: %i[ show update destroy ]
# GET /authors
def index
@authors = Author.includes(:books).all
render json: AuthorSerializer.new(@authors)
end
# GET /authors/1
def show
render json: AuthorSerializer.new(@author)
end
# POST /authors
def create
@author = Author.new(hospital_params)
if @author.save
render json: @author, status: :created, location: @author
else
render json: @author.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /authors/1
def update
if @author.update(author_params)
render json: @author
else
render json: @author.errors, status: :unprocessable_entity
end
end
# DELETE /authors/1
def destroy
@author.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_author
@author= Author.find(params[:id])
end
# Only allow a list of trusted parameters through.
def author_params
params.require(:author).permit(:id, :fname, :lname, :avatar[])
end
end