Rails 7:如何在 jsonapi 序列化器中包含嵌套关联

问题描述 投票:0回答:1

我有一个作者,他有很多书,还有一本属于 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
json ruby associations ruby-on-rails-7 jsonapi-serializer
1个回答
0
投票

您可以通过多种方式从 Ruby on Rails 中的关联模型获取关联数据:

我只分享两种方法:

  1. 您可以使用 as_json

示例:

user.as_json(include: { posts: {
                       include: { comments: {
                                      only: :body } },

更多详情:看这里

  1. 您可以使用红宝石-葡萄宝石。您可以获得关联的数据,并且它有很多自定义功能。只需查看文档即可。 葡萄宝石

如果您有任何困惑,请告诉我。谢谢你。

© www.soinside.com 2019 - 2024. All rights reserved.