如何使用ActiveModel :: Serializers为同一模型实现多个不同的序列化器? [英] How to implement multiple different serializers for same model using ActiveModel::Serializers?
问题描述
假设您正在Rails中实现REST API.在提供集合时,您可能只希望包含一些属性:
Let's say you're implementing a REST API in Rails. When serving a collection, you might want to only include a few attributes:
/people
但是在提供单个资源时,您要包括所有属性:
But when serving a single resource, you want to include all the attributes:
/people/1
我不知道如何使用ActiveModel :: Serializers来执行此操作,因为所有示例均使用了为每个模型定义一个序列化器的模式(具有标准命名约定),并且当出现以下情况时,让AMS在控制器中自动使用正确的序列化器你这样做:
I don't see how to do that using ActiveModel::Serializers, since the examples all use the pattern of defining one serializer per model (with a standard naming convention) and having AMS automatically use the right one in the controller when you do:
render json: @people
或:
render json: @person
推荐答案
为避免将视图关注点混入模型(通过序列化变体),请使用视图为每个操作呈现JSON,就像我们对HTML所做的一样.
To avoid mixing view concerns into your models (via serialized variations), use the view to render your JSON for each action, much like we do for HTML.
jbuilder & rabl 都很好地满足了这种数据模板需求.
jbuilder & rabl both fill this data templating need quite nicely.
更新2013-12-16 : ActiveModelSerializers 库可以通过使用 查看全文