Search code examples
rubyserializationruby-on-rails-5active-model-serializers

Set a custom serializer in the include file with rails 5


I have this code that brings one vacancy from my model Vacancy and then render in json the attributes according to the serializer VacancyDetailSerializer:

Controller

vacancy = Vacancy.find(params[:id])    
render json: vacancy, serializer: VacancyDetailSerializer, 
                      include: [:restaurant]

The thing here is that in the include: [:restaurant] I want to specify a custom serializer the way I did with vacancy, because right now is taking the serializer of RestaurantSerializer, but I don't want to take that file, is there a way to do it with the include? Maybe is here in the controller, or maybe in the serializer?


Solution

  • If you have belongs_to :restaurant association in the VacancyDetailSerializer, then serializer for this association can be specified:

    class VacancyDetailSerializer < ActiveModel::Serializer
      belongs_to :restaurant, serializer: AnotherRestaurantSerializer
    end
    

    Or it can be overridden by providing a block:

    class VacancyDetailSerializer < ActiveModel::Serializer
      belongs_to :restaurant do
        AnotherRestaurantSerializer.new(object.restaurant)
      end
    end
    

    Or a custom association serializer lookup can be implemented.