From 9e2b7e267e4a160b9538430b0da02b291283af68 Mon Sep 17 00:00:00 2001 From: Devin Howard Date: Wed, 11 Jan 2017 23:18:23 -0500 Subject: [PATCH] fix has_many api embeds too! --- .../api/v2/application_serializer.rb | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/app/serializers/api/v2/application_serializer.rb b/app/serializers/api/v2/application_serializer.rb index d7c6d6da..bfd323f0 100644 --- a/app/serializers/api/v2/application_serializer.rb +++ b/app/serializers/api/v2/application_serializer.rb @@ -34,17 +34,28 @@ module Api opts.merge(unless: -> { embeds.include?(key) })) do 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)) || [] + has_many(attr, opts.merge(if: -> { embeds.include?(key) })) do |serializer| + 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) })) do |serializer| - child_object = serializer.object.send(key) - child_serializer = "Api::V2::#{child_object.class.name}Serializer".constantize - resource = child_serializer.new(child_object, scope: serializer.scope.merge(embeds: [])) + 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