How to select serializer for nested objects with active_model_serializers

北战南征 提交于 2019-12-06 03:52:22

问题


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.

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
  }
}

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

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

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.


回答1:


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)}

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.



来源:https://stackoverflow.com/questions/21271597/how-to-select-serializer-for-nested-objects-with-active-model-serializers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!