您可以为显示不同内容的同一模型设置两个序列化器吗?

Can you have two serializers for the same model that shows different things?

我想区分用户在我的 API 中看到的内容,当他们想要查看所有对象时以及他们想要查看特定对象时。是否可以这样做并且仍然与该特定模型相关?

Is it possible to do that and still relate to that particular model?

是的,可以为任何对象创建多达 serializer 个对象。

假设 User 是一个模型

所以可以有两个serializer

1 => UserSerializer # 用户对象 serializer 的默认值

2 => CustomUserSerializer #这是用户对象的另一个自定义序列化程序

To use it

1 => render json: user, status: 200 # 这将调用默认 UserSerializer

2 => render json: user, serializer: CustomUserSerializer, status: 200 # 这将调用 CustomUserSerializer

参考 - Custom ActiveModel::Serializers