From a9f19815e4688bb05f5013185f5e460648fdf73b Mon Sep 17 00:00:00 2001 From: Devin Howard Date: Thu, 19 Jan 2017 14:49:40 -0500 Subject: [PATCH] fix api embed to use the correct serializers (fix #998) (#1029) * use correct serializer for singular embeds in api (almost fixes #998) * fix has_many api embeds too! * unused arg --- .../api/v2/application_serializer.rb | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/app/serializers/api/v2/application_serializer.rb b/app/serializers/api/v2/application_serializer.rb index 4345c941..81772577 100644 --- a/app/serializers/api/v2/application_serializer.rb +++ b/app/serializers/api/v2/application_serializer.rb @@ -35,13 +35,29 @@ module Api Pundit.policy_scope(scope[:current_user], object.send(attr))&.map(&:id) || [] end has_many(attr, opts.merge(if: -> { embeds.include?(key) })) do - Pundit.policy_scope(scope[:current_user], object.send(attr)) || [] + list = Pundit.policy_scope(scope[:current_user], object.send(attr)) || [] + child_serializer = "Api::V2::#{attr.to_s.singularize.camelize}Serializer".constantize + resource = ActiveModelSerializers::SerializableResource.new( + list, + each_serializer: child_serializer, + scope: scope.merge(embeds: []) + ) + resource.as_json end else id_opts = opts.merge(key: "#{key}_id") attribute("#{attr}_id".to_sym, id_opts.merge(unless: -> { embeds.include?(key) })) - attribute(key, opts.merge(if: -> { embeds.include?(key) })) + attribute(key, opts.merge(if: -> { embeds.include?(key) })) do |serializer| + object = serializer.object.send(key) + child_serializer = "Api::V2::#{object.class.name}Serializer".constantize + resource = ActiveModelSerializers::SerializableResource.new( + object, + serializer: child_serializer, + scope: scope.merge(embeds: []) + ) + resource.as_json + end end end end