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

时间:2019-04-16 22:39:48

标签: ruby-on-rails active-model-serializers

I want to differentiate what the user sees in my API when they want to see all the objects and when they want a specific object. Is it possible to do that and still relate to that particular model?

1 个答案:

答案 0 :(得分:0)

  

是否有可能这样做并且仍然与该特定模型相关?

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

假设User是一个模型

所以可以有两个serializer

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

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

  

要使用它

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

2 => render json: user, serializer: CustomUserSerializer, status: 200#这将称为CustomUserSerializer

参考-Custom ActiveModel::Serializers