3
votes

I'm trying to use active_model_serializers in Rails 4.0.0 to serialize my json responses. However, the AMS class does not seem to be getting called/used at all when I use

render json: user

I'm not sure if there is some configuration issue, or if I'm using namespaces incorrectly.

Gemfile has:

gem 'active_model_serializers', '0.8.0'

Controller (in app/controllers/api/v1/users_controller.rb):

module API
  module V1
    class UsersController < API::V1::BaseController
      def show
        user = User.find(params[:id])
        render json: user
      end
    end
  end
end

UserSerializer (in app/serializers/user_serializer.rb)

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name
end

But in the json response I'm still seeing the full object, i.e.

{"id":1,"first_name":"Test","last_name":"User1","created_at":"2013-12-26T07:12:02.618Z","updated_at":"2013-12-26T07:12:02.618Z"}

I've tried everything from explicitly calling render json: user, serializer: UserSerializer to namespacing the serializer to API::V1 and the result is the same. Am I missing something here?

Edit: This was fixed by making my BaseController inherit from ActionController::Base rather than ActionController::Metal. Not entirely sure what was missing from ActionController::Metal, though.

2

2 Answers

1
votes

I had a similar problem on Rails3 and I had to add this line into the app initializer folder

ActionController::API.send(:include, ActionController::Serialization)

Check if you have to do something similar with yours like

ActionController:: Metal.send(:include, ActionController::Serialization)
1
votes

include ActionController::Serialization

in ApplicationController