Search code examples
ruby-on-railsjsonactive-model-serializers

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).


Solution

  • 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.