如何在序列化程序中迭代哈希数组

问题描述 投票:0回答:1

我有一个分组的集合,我想对其进行序列化,但是它返回一个错误'#的未定义方法'read_attribute_for_serialization'。这是我的不带序列化器的示例数据:

{
    "message": "success",
    "data": {
        "reports": {
            "export": [
                {
                    "name": "Order",
                    "report_type": "export",
                    "parameters": "\"{order_date: '10-10-2019'}\"",

                },
                {
                    "name": "Order",
                    "report_type": "export",
                    "parameters": "\"{order_date: '10-10-2019'}\"",
                }],
            "import": [
                {
                    "name": "Order",
                    "report_type": "import",
                    "parameters": "\"{order_date: '10-10-2019'}\"",
                },
                {
                    "name": "Order",
                    "report_type": "import",
                    "parameters": "\"{order_date: '10-10-2019'}\"",
                }
            ],
            "details": [
                {
                    "name": "Order",
                    "report_type": "details",
                    "parameters": "\"{order_date: '10-10-2019'}\"",
                },
                {
                    "name": "Order",
                    "report_type": "details",
                    "parameters": "\"{order_date: '10-10-2019'}\"",
                }
            ]
        }
    }
}

这是我的序列化器:


class ReportSerializer < ActiveModel::Serializer
  attributes :id, :name, :report_type, :parameters

  def parameters
    JSON.parse(object.parameters)
  end
end

这是我的控制器代码:

  def reports_list
    reports = Report.all.group_by(&:report_type)
    render_collection(reports, { name: 'reports' }, each_serializer: ReportSerializer)
  end

但是给我返回错误:undefined method `read_attribute_for_serialization' for #<Hash:0x0000562eebbddee8>

请帮助。谢谢。

ruby-on-rails ruby active-model-serializers
1个回答
0
投票

[*.group_by()是返回哈希的Enumerable方法-我认为render_collection希望接收ActiveRecord::Relation-改用*.group(:report_type)

© www.soinside.com 2019 - 2024. All rights reserved.