ActiveModel :: Serializer为空的has_one关系(而不是JSON)返回null

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

问题

我们的API应该返回JSON对象(但不返回JSON API)。我们如何更改ActiveModel :: Serializer来创建数据属性设置为null的JSON对象?

我们为空(has_one关系)资源获得的响应为NULL,但我们希望它采用JSON格式{data:NULL},就像我们收到的非空资源{data:{...} },或者用于列表(has_many关系)资源{data:[]}。

我们尝试过的

我们使用ActiveModel :: Serialiser并指定要命名为“数据”的键,而不是资源名称(类似于JSON API,但是数据的内容是实体的直接JSON表示。)>]

模型

class User < ApplicationRecord
  has_one :profile

  def serializer_class
    V1::UserSerializer
  end
end

class Profile < ApplicationRecord
  belongs_to :user

  def serializer_class
    V1::ProfileSerializer
  end
end

Serializers >>:

class ApplicationSerializer < ActiveModel::Serializer
  def json_key
    'data'
  end
end

class UserSerializer < ApplicationSerializer
  attributes :id, :created_at, :updated_at #we do not include the profile here
end

class ProfileSerializer < ApplicationSerializer
  attributes :id, :created_at, :updated_at
end

Controllers

class ProfilesController < ::ApplicationController
  before_action :authenticate_user!
  def show
    @profile = current_user.profile
    render json: @profile
  end
end

响应

我们收到(对于我们来说是错误的)对空资源(GET / profile)的响应:

NULL

我们正确地获得了一个非空资源的响应,它看起来像这样(不是JSON API):

{
  data: {
    id: ...,
    name: ...,
    createdAt: ...,
  }
}

我们想要什么

[我们希望在没有关联的实体的情况下,回复的格式如下:

{
  data: null
}

问题我们的API应该返回JSON对象(但不返回JSON API)。我们如何更改ActiveModel :: Serializer以创建数据属性设置为null的JSON对象?我们得到一个空(...

ruby-on-rails json serializer
1个回答
0
投票

我发现此(解决方法)解决方案解决了问题:

  def show
    if @profile
      render json: @profile
    else
      render json: {data: nil}
    end
  end
© www.soinside.com 2019 - 2024. All rights reserved.