Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveModel::Serializer belongs_to attribute is not being displayed in json response

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?

like image 672
Nick ONeill Avatar asked Dec 02 '25 09:12

Nick ONeill


1 Answers

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
like image 113
fabriciofreitag Avatar answered Dec 04 '25 01:12

fabriciofreitag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!