3

I'm not quite sure why this isn't working but I have the following serializer:

class ExternalAccountSerializer < ActiveModel::Serializer
  attributes :id, :account_name, :type

  belongs_to :user, serializer: UserSerializer
end

The API is returning the following:

{
    "external_account":{
        "id":3,"account_name":"Company Inc.","type":"External service"
    }
}

The external account is being returned but the user is not. Any ideas why that is? How can I ensure this is displayed?

Nick ONeill
  • 7,341
  • 10
  • 47
  • 61

2 Answers2

3

I believe you must include :user on your attributes:

 attributes :id, :account_name, :type, :user

and then:

def user
  UserSerializer.new(object.user, root: false)
end
fabriciofreitag
  • 2,843
  • 22
  • 26
0

Here is my solution: I had to include the user in the controller.

posts_controller.rb

  ...
  render json: post,
      include: 'user', # include user for custom serializer to work
   serializer: Api::V1::Post::PostSerializer,
       status: :created
Pascal
  • 1,158
  • 17
  • 20
  • docs: https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/adapters.md#include-option – Pascal Apr 18 '18 at 20:12