我正在学习如何使用 active_model_serializers
( gem )。在组织序列化器中,我有:
has_many :nodes
现在,当我对组织的数据发出 API 请求时,它还会自动发送关联节点的属性。
例如,对组织 Controller 的 show 方法发出 GET 请求,会生成包含组织属性和节点的 JSON。这有效。
这对于 show 方法来说是完美的,但对于对索引方法的 GET 请求,我希望它仅包含组织的属性,而不包含关联节点的属性。这可能吗?
最佳答案
您可以为不同的操作创建不同的序列化器:
class ShallowOrganizationSerializer < ActiveModel::Serializer
attributes :id, :name # ....
end
class DetailedOrganizationSerializer < ShallowOrganizationSerializer
has_many :nodes
end
在你的 Controller 中:
class OrganizationController < ApplicationController
def index
# ...
render json: @organizations, each_serializer: ShallowOrganizationSerializer
end
def show
# ...
render json: @organization, serializer: DetailedOrganizationSerializer
end
end
关于ruby-on-rails - 如何让序列化器不包含仅用于特定方法的关联表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34842872/