Rails - 活动模型在序列化程序中序列化哈希数组
Rails - active model serialize an array of hashes within a serializer
我正在尝试创建一个嵌套的序列化哈希数组。到目前为止,我有以下内容。它不是 return 嵌套的序列化器,而是哈希数组。
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
但它 return 如下
{
"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
当您渲染对象时(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
我正在尝试创建一个嵌套的序列化哈希数组。到目前为止,我有以下内容。它不是 return 嵌套的序列化器,而是哈希数组。
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
但它 return 如下
{
"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
当您渲染对象时(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