如何使用active_model_serializers为嵌套对象选择序列化程序 [英] How to select serializer for nested objects with active_model_serializers

查看:128
本文介绍了如何使用active_model_serializers为嵌套对象选择序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用rails 4.0.0,并且正在寻找一种使用这些预定义对象的序列化程序序列化包含预定义对象的自定义对象的方法.

I am using rails 4.0.0 and am looking for a way to serialize a custom object which contains predefined objects with these predefined object's serializers.

示例:我有一个带有序列化器StudentSerializer的模型Student.我想呈现一个JSON对象,如下所示:

Example: I have a model Student with a serializer StudentSerializer. I want to render a JSON object as follows:

{ 
  user_type: "student"
  student: {
    id: 1
    email: fake@email.com
  }
}

我为学生编写的序列化程序仅序列化电子邮件和id属性.但是当我打电话时:

My serializer written for Student only serializes the email and id attributes. However when I call:

render json: {user_type="student", student: stu}

我获得了具有所有属性的学生的完整对象.是否有可能为JSON响应中的嵌套对象选择一个带有active_model_serializers的序列化器?

I get the full object of student back with all attributes. Is it possible to pick a serializer with active_model_serializers for nested objects in a JSON resposne?

一种可能的解决方案可能是编写一个新的序列化器,该序列化器包含我刚刚描述的整个对象,并将其用作序列化器,但我宁愿避免这种情况.

A possible solution may be to write a new serializer which encompasses the whole object I just described and have that used as the serializer, but I would rather avoid this if possible.

推荐答案

我找到了解决方案.它不能自动执行,但是您可以使用以下命令对嵌套对象强制执行序列化程序:

I found a solution. It cannot be performed automatically but you can force a serializer on a nested object by using:

render json: {user_type: "student", student: StudentSerializer.new(stu)}

一个有趣的注释是,提起请求已提交,并且对于active_model_serializers https://github.com /rails-api/active_model_serializers/pull/300 会自动执行此任务.

An interesting note is that a pull request was submitted and remains in limbo for active_model_serializers https://github.com/rails-api/active_model_serializers/pull/300 which would preform this task automatically.

这篇关于如何使用active_model_serializers为嵌套对象选择序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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