Search code examples
ruby-on-railsruby-on-rails-4active-model-serializers

ActiveModelSerializers isn't used for render json


I am using version 0.9.3 of Active Model Serializers. When I call render json: @collection or even an individual object it uses the default to_json method and returns the full object. Im not trying anything fancy. My controllers are in the directory app/controllers/v1/ and the serializers are in the directory app/serializers/v1/ and I have also tried them in app/serializers/. The serializer class name is UserSerializer and the model is User. Any ideas why this may be happening would be great.


Solution

  • If it's a collection of objects, specify the each_serializer when you render:

      render(
        json: @collection,
        each_serializer: UserSerializer
      )
    

    If it's a single object, then specify the serializer:

      render(
        json: @user,
        serializer: UserSerializer
      )