繁体   English   中英

ActiveModel::Serializers JSON API 嵌套关联需要包含一个值

[英]ActiveModel::Serializers JSON API nested associations needs to include a value

我有一个 Rails 7 API 并且我正在使用gem 'active_model_serializers', '~> 0.10.0'使 het 符合 json_api 要求,但我需要在我的项目的嵌套属性中包括名称,而不仅仅是id 和 type,我尝试了很多我在互联网上找到的东西,但没有一个能为我解决这个问题,我希望这里有人可以。

我的 products_controller.rb

class ProductsController < ApplicationController

  include ActionController::HttpAuthentication::Token::ControllerMethods
  before_action :authenticate

  include ErrorSerializer

  before_action :set_product, only: %i[ show update destroy ]

  # GET /products
  def index
    page_number = params[:page].try(:[], :number)
    per_page = params[:page].try(:[], :size)


    @products = Product.all.page(page_number).per(per_page)

    # paginate json: @products
    render json: @products, show_category: (param? params[:category]), show_unit: (param? params[:unit])
  end

  def all
    @products = Product.all

    render json: @products
  end

  # GET /products/1
  def show
    render json: @product
  end

#The rest of crud options

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def product_params
      params.require(:product).permit(:name, :description, :quantity_in_stock, :price, :highlight, :category_id, :unit_id)
    end

    def authenticate
      authenticate_or_request_with_http_token do |token, options|
        hmac_secret = ENV['TOKEN']
        JWT.decode token, hmac_secret, true, { :algorithm => 'HS256' }
      end
    end
end

我的 product_serializer

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :quantity_in_stock, :price, :highlight
  
  belongs_to :category, optional: true
  belongs_to :unit, optional: true

  def should_render_category
    @instance_options[:show_category]
  end
  def should_render_unit
    @instance_options[:show_unit]
  end
end

我的unit_serializer:

class UnitSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :products, optional: true
end

我的category_serializer:

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :products, optional: true
end

和我的 application_controller:

class ApplicationController < ActionController::API
  before_action :ensure_json_request

  def param? param

    param && param != "false" && param != "nil"
  
  end

  def ensure_json_request
    unless request.headers["Accept"] =~ /vnd\.api\+json/
      render body: nil, :status => 406
    else
      unless request.get?
        return if request.headers["Content-Type"] =~ /vnd\.api\+json/
        render body: nil, :status => 415
      end
    end
  end
end

而我的实际回应:

{
            "id": "1",
            "type": "products",
            "attributes": {
                "name": "Lightweight Iron Keyboard",
                "description": "Sit quas ipsa. Animi non omnis. Eveniet et quidem.",
                "quantity-in-stock": 99,
                "price": 27.88,
                "highlight": false
            },
            "relationships": {
                "category": {
                    "data": {
                        "id": "4",
                        "type": "categories"
                    }
                },
                "unit": {
                    "data": {
                        "id": "2",
                        "type": "units"
                    }
                }
            }
        }

如评论所述,您应该寻找替代品,因为不再维护此宝石

关于您的问题,文档说要指定序列化程序所以要修改:

class ProductSerializer < ActiveModel::Serializer
  # ...
  
  belongs_to :category, optional: true, serializer: MyCategorySerializer
  # ...
class MyCategorySerializer < ActiveModel::Serializer
  attributes :id, :name, :type
end

并对UnitSerializer执行相同的操作,它应该可以顺利工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM