Rails-活动模型将序列化器中的哈希数组序列化

时间:2018-10-04 08:34:46

标签: ruby-on-rails ruby active-model-serializers rails-api

我正在尝试创建一个嵌套的哈希序列化数组。到目前为止,我有以下内容。它不返回嵌套的序列化器,而仅返回哈希数组。

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

和其他序列化器

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


      def var
        "var"
      end
    end
  end
end

但它返回以下内容

{
    "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"
                }
            ]
        }
    }
}

所以我不认为它正在使用ReportBuildSerializer

1 个答案:

答案 0 :(得分:3)

渲染对象(reports)时,可能会在controller中。您可以确保这样做吗?

render json: @reports, include: 'reports'

如果它不起作用,则可以采用另一种方法:

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