Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top