gpt4 book ai didi

ruby-on-rails - Rails - 事件模型序列化序列化程序中的哈希数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:58:16 25 4
gpt4 key购买 nike

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

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

最佳答案

当您渲染您的对象(报告)时,可能在 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

关于ruby-on-rails - Rails - 事件模型序列化序列化程序中的哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52642390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com