Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select serializer for nested objects with active_model_serializers

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: [email protected]
  }
}

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.

like image 200
Jordan Ell Avatar asked Jan 22 '14 00:01

Jordan Ell


1 Answers

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.

like image 113
Jordan Ell Avatar answered Oct 11 '22 07:10

Jordan Ell