如何使用ActiveModel :: Serializers为同一模型实现多个不同的序列化器? [英] How to implement multiple different serializers for same model using ActiveModel::Serializers?

查看:82
本文介绍了如何使用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 库可以通过使用 查看全文

相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆