ActiveModelSerializer:如何向自定义属性添加关联?

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

我有一个具有自定义属性的序列化程序,我需要包括与该自定义属性的关联,但无法弄清楚:

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,
                           .......
                        }
                    ]
                },
            .........
            ]
        },
ruby-on-rails active-model-serializers
1个回答
0
投票

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

def your_action
  # ...
  render(
    :json,
    include: 'your_relationship',
    # ...
  )
end
© www.soinside.com 2019 - 2024. All rights reserved.