ActiveModelSerializer:如何将关联添加到自定义属性



我有一个带有自定义属性的序列化程序,我需要包含与该自定义属性的关联,但无法解决:

def dependent_integrations
object.integrations.includes(:service_integrations).where(service_integrations: { master: false}).map do |integration|
# this.integration.organization_integrations ===> I need to include organization_integrations into to integration object for serializer
end
end

获取代码的JSON:

"dependent_integrations": [
{
"id": 2,
"name": "Confluence Cloud",
"key": "confluence-cloud",
"description": "blablaabla",
"vendor": "Atlassian",
"active": true,
"created_at": "2020-04-08T18:16:01.000Z",
"updated_at": "2020-04-08T18:16:03.000Z",
"custom": false
},
]
},

但我需要获得以下包含organization_integrations的JSON:

"dependent_integrations": [
{
"id": 2,
"name": "Confluence Cloud",
"key": "confluence-cloud",
"description": "blablaabla",
"vendor": "Atlassian",
"active": true,
"created_at": "2020-04-08T18:16:01.000Z",
"updated_at": "2020-04-08T18:16:03.000Z",
"custom": false,
"organization_integrations": [
{
id: 1,
.......
},
{
id: 2,
.......
}
]
},
.........
]
},

尝试在渲染方法中使用include选项。

def your_action
# ...
render(
:json,
include: 'parent_model.integrations.service_integrations',
# ...
)
end

您想要的是在序列化程序中呈现一个关联。您需要做的是为正在渲染的每个模型使用不同的序列化程序。请注意,您没有指定您使用的rails的版本,因此以下代码可能无法正常工作

# your serializer
def dependent_integrations
ActiveModel::Serializer::CollectionSerializer.new(integrations, each_serializer: IntegrationSerializer).as_json
end
private
def integrations
object.integrations.includes(:service_integrations).where(service_integrations: { master: false })
end
# IntegrationSerializer
class IntegrationSerializer < ActiveModel::Serializer
attributes :id, :name, :key, :description, :vendor, :created_at, :updated_at, :custom, :organization_integrations
def organization_integrations
ActiveModel::Serializer::CollectionSerializer.new(object.organization_integrations, each_serializer: OrganizationIntegrationSerializer).as_json
end
end
# OrganizationIntegrationSerializer
class OrganizationIntegrationSerializer
attributes :id # ...
end

最新更新