Search code examples
ruby-on-railsrubyjsonserializationactive-model-serializers

How to have a serializer not include an associated table only for a specific method?


I'm learning how to use active_model_serializers (gem). In an organization serializer I have:

has_many :nodes

So now when I make an API request for the data for an organization, it automatically also sends the attributes for the associated nodes.

For example, a GET request to the show method of the organizations controller, generates JSON that includes attributes for organization as well as the nodes. This works.

This is perfect for the show method, but for a GET request to the index method I would like it to only include the attributes for the organization and not for the associated nodes. Is this possible?


Solution

  • You can create different serializers for different actions:

    class ShallowOrganizationSerializer < ActiveModel::Serializer
        attributes :id, :name # ....
    end
    
    class DetailedOrganizationSerializer < ShallowOrganizationSerializer
        has_many :nodes
    end
    

    And in your controller:

    class OrganizationController < ApplicationController
        def index
            # ...
            render json: @organizations, each_serializer: ShallowOrganizationSerializer
        end
    
        def show
            # ...
            render json: @organization, serializer: DetailedOrganizationSerializer
        end
    end