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

查看:16
本文介绍了如何使用 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 库支持为一个模型定义多个序列化程序,正如@phaedryx 稍后回答的那样,通过使用 自定义序列化程序.

Update 2013-12-16: The ActiveModelSerializers library does support defining multiple serializers for one model, as @phaedryx answered later, by using custom serializers.

这篇关于如何使用 ActiveModel::Serializers 为同一模型实现多个不同的序列化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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