我有一个分组的集合,我想对其进行序列化,但是它返回一个错误'#的未定义方法'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>
请帮助。谢谢。
[*.group_by()
是返回哈希的Enumerable
方法-我认为render_collection希望接收ActiveRecord::Relation
-改用*.group(:report_type)