Search code examples
ruby-on-railsrubyactive-model-serializersrails-api

Rails - active model serialize an array of hashes within a serializer


I am trying to create a nested serialized array of hashes. I have the following so far. It doesn't return the nested serializer but just the array of hashes.

module Api
  module V1
    class ReportShowSerializer < ActiveModel::Serializer
      attributes :name, :schedule, :uuid, :reports

       has_many :reports, each_serializer: ReportBuildSerializer

      def reports
        [
          {date: '2018-10-04', test: 'a'},
          {date: '2018-10-03', test: 'b'}
        ]
      end
    end
  end
end

and the other serializer

module Api
  module V1
    class ReportBuildSerializer < ActiveModel::Serializer
      attributes :test, :date, :var


      def var
        "var"
      end
    end
  end
end

but it returns the following

{
    "data": {
        "id": "2",
        "type": "reports",
        "attributes": {
            "name": "Another test report",
            "schedule": "weekly",
            "uuid": "f10736ae-bf5c-4e43-8cd4-35eb0dc12efd",
            "reports": [
                {
                    "date": "2018-10-04",
                    "test": "ff"
                },
                {
                    "date": "2018-10-03",
                    "test": "ff"
                }
            ]
        }
    }
}

So I don't think it is using the ReportBuildSerializer


Solution

  • When you render your objects(reports) probably in the controller. Could you make sure that you do it like this:

    render json: @reports, include: 'reports'
    

    If it does not work then you can go with another approach:

    module Api
      module V1
        class ReportShowSerializer < ActiveModel::Serializer
          attributes :name, :schedule, :uuid, :reports
    
           has_many :reports, each_serializer: ReportBuildSerializer
    
          def reports
            [
              ::Api::V1:: ReportBuildSerializer.new({date: '2018-10-04', test: 'a'}).attributes,
              ::Api::V1:: ReportBuildSerializer.new({date: '2018-10-03', test: 'b'}).attributes
            ]
          end
        end
      end
    end