Daniel Viglione
Daniel Viglione

Reputation: 9407

active model serializer not showing all attributes of associated model

I have an Item. It belongs_to a User. I have an ItemSerializer and a UserSerializer in app/serializers:

class ItemSerializer < ActiveModel::Serializer
  attributes :id, :photo

  belongs_to :user
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :authentication_token
end

These relationships model the relationships in app/models

When I return an ActiverRecord::Relation of items as json in my controller:

def index
    respond_to do |format|
      @items = Item.where(id: params[:item_ids)
      format.html
      format.json { render json: @items, status: 200}
    end
  end

It should be returning the user attributes, including email and authentication_token, as well. But it is only returning the user id:

... "relationships":{"user":{"data":{"id":"1","type":"users"}}} ...

What am I doing wrong?

Upvotes: 1

Views: 1669

Answers (2)

Daniel Viglione
Daniel Viglione

Reputation: 9407

I figured out the issue. I am using active_model_serializers version 0.10.0. In config/environments/initialzers/active_model_serializer.rb, I had the following configuration:

ActiveModel::Serializer.config.adapter = :json_api

When I changed it to:

ActiveModel::Serializer.config.adapter = :json

It gave me the attributes of the associations as well, as illustrated from the console:

ActiveModelSerializers::SerializableResource.new( Item.where(id: params[:item_ids), adapter: :json).to_json

Upvotes: 0

Chris
Chris

Reputation: 11

Try doing

render json: @items, include: "**", status: 200

In your controller. AMS can be finicky in returning related object attributes so sometimes you need to be explicit about it.

Upvotes: 1

Related Questions