Omar Lahlou
Omar Lahlou

Reputation: 1000

Ruby On Rails 4 - Serializers not called

I am working on building a JSON API using Ruby-On-Rails 4.

To serialize my JSON responses, I use active_model_serializers version 0.9.4.

I have an ApiController which inherits from ApplicationController. All my controllers inherit from ApiController.

Here is what ApiController looks like:

class Api::ApiController < ApplicationController
  include ActionController::Serialization
  private

    def respond_with_json(payload)
      render json: payload, root: false, status: 200
    end
end

I've created a FriendshipSerializer, associated to Friendship Model, using rails g serializer friendship. This generated the following file:

class FriendshipSerializer < ActiveModel::Serializer
  attributes :id, :image
end

Here is the code of friendships#index controller action:

def index
  friendships = current_user.friendships.order(created_at: "DESC")
  respond_with_json(friendships)
end

The problem I am currently encountering is when calling friendships#index controller action, it returns a JSON array with all Friendship Model data, while it is supposed to return only ids(according to FriendshipSerializer).

Upvotes: 0

Views: 1190

Answers (2)

prusswan
prusswan

Reputation: 7091

Since it works when the serializers are explicitly specified, I suspect this is a known issue (autoloading of serializers not working in some cases, which may or may not be a bug as this might be caused by interference from other gems). If you can live with this (or find a workaround), you can continue to work with 0.9 (which is more "battle-tested"), otherwise try to use the current version 0.10. Note that there are some major changes between these versions.

Upvotes: 1

Wil Chandler
Wil Chandler

Reputation: 68

I notice a few spelling inconsistencies in your question. Are you sure the classnames of the model and serializer match? For example, if your model class is named "Friendship," AMS will look for a serializer named "FriendshipSerializer." If AMS does not find that serializer, I believe it will still render the record's attributes independently of a serializer; so if you've got a "Friendship" model and "FrienshipSerializer" (or vice versa), that could be the problem.

Upvotes: 1

Related Questions