Jeremy Thomas
Jeremy Thomas

Reputation: 6684

Choose serializer for nested association

I am using Active Model Serializer in my Rails API but cannot get the nested serializers to work (I believe due to the fact that I have multiuple serializers for the same resource). My models are setup such that:

class Program < ActiveRecord::Base
    acts_as_paranoid
    has_many :check_ins
end

class CheckIn < ActiveRecord::Base
    has_one :weigh_in, dependent: :destroy
end

class WeighIn < ActiveRecord::Base
    belongs_to :check_in
end

In my ProgramsController I have the following:

def index
    programs = Client.find(params[:client_id]).programs
    render json: programs, status: :ok, each_serializer: API::ProgramSerializer, include: "**"
end

And in my API::ProgramSerializer I have the following:

class API::ProgramSerializer < ActiveModel::Serializer
    attributes :created_at, :position, :id

    has_many :check_ins, each_serializer: API::CheckInsIndexSerializer
end

The issue I'm running into is that I have both an API::CheckInsIndexSerializer as well as an API::CheckInSerializer. It seems like the include: "**" forces Rails to use the API::CheckInSerializer despite me specifying that I'd like to use the API::CheckInsIndexSerializer. Is there a way around this?

Upvotes: 0

Views: 704

Answers (1)

Jeremy Thomas
Jeremy Thomas

Reputation: 6684

I was able to solve this by modifying both the ProgramsController and the API::ProgramSerializer the following:

def index
    programs = Client.find(params[:client_id]).programs
    render json: programs, status: :ok, each_serializer: API::ProgramSerializer
end

class API::ProgramSerializer < ActiveModel::Serializer
    attributes :created_at, :position, :id, :check_ins

    def check_ins
        ActiveModel::SerializableResource.new(object.check_ins,  each_serializer: API::CheckInsIndexSerializer)
    end
end

I had to remove the include: "**" and define how to load the check_ins explicitly.

Upvotes: 1

Related Questions