如何让序列化程序不包含仅针对特定方法的关联 table?
How to have a serializer not include an associated table only for a specific method?
我正在学习如何使用 active_model_serializers
(gem)。在组织序列化程序中,我有:
has_many :nodes
所以现在当我为组织发出 API 数据请求时,它也会自动发送关联节点的属性。
例如,对组织控制器的显示方法的 GET 请求生成 JSON,其中包括组织和节点的属性。这行得通。
这非常适合显示方法,但对于对索引方法的 GET 请求,我希望它只包含组织的属性,而不包含关联节点的属性 .这可能吗?
您可以为不同的操作创建不同的序列化程序:
class ShallowOrganizationSerializer < ActiveModel::Serializer
attributes :id, :name # ....
end
class DetailedOrganizationSerializer < ShallowOrganizationSerializer
has_many :nodes
end
在你的控制器中:
class OrganizationController < ApplicationController
def index
# ...
render json: @organizations, each_serializer: ShallowOrganizationSerializer
end
def show
# ...
render json: @organization, serializer: DetailedOrganizationSerializer
end
end
我正在学习如何使用 active_model_serializers
(gem)。在组织序列化程序中,我有:
has_many :nodes
所以现在当我为组织发出 API 数据请求时,它也会自动发送关联节点的属性。
例如,对组织控制器的显示方法的 GET 请求生成 JSON,其中包括组织和节点的属性。这行得通。
这非常适合显示方法,但对于对索引方法的 GET 请求,我希望它只包含组织的属性,而不包含关联节点的属性 .这可能吗?
您可以为不同的操作创建不同的序列化程序:
class ShallowOrganizationSerializer < ActiveModel::Serializer
attributes :id, :name # ....
end
class DetailedOrganizationSerializer < ShallowOrganizationSerializer
has_many :nodes
end
在你的控制器中:
class OrganizationController < ApplicationController
def index
# ...
render json: @organizations, each_serializer: ShallowOrganizationSerializer
end
def show
# ...
render json: @organization, serializer: DetailedOrganizationSerializer
end
end