Rails active_model_serializers not working

338 Views Asked by At

This is my first time to use active_model_serializers gem, I have been looking around the documentation and have not found a solution.

I have followed all the Getting Started documentation but when I try to get the serialized record I get standard rails JSON not serialized record.

I found a similar thread in SO : active_model_serializers not working in rails-api, in this thread many people said that we need to manually add include ActionController::Serialization in our ApplicationController. I also have followed, but nothing work. Can anyone help me to solve this problem ?

Controller :

class AdministratorsController < ApplicationController
    def login
        @administrator = Administrator.find_by(username: params[:username])

        if @administrator && @administrator.authenticate(params[:password])
            token = encode_token({ administrator_id: @administrator.id })
            render json: { administrator: @administrator, token: token }
        else
            render json: { error: 'Username atau Passowrd anda salah !' }, status: :unauthorized
        end
    end
end

Serializer :

class AdministratorSerializer < ActiveModel::Serializer
  attributes :id, :full_name, :username
end 

Actual Response :

{
    "administrator": {
        "id": 1,
        "full_name": "Kevin Jayden Wivano",
        "username": "kevin",
        "password_digest": "blablabla",
        "created_at": "2021-10-23T15:36:15.793Z",
        "updated_at": "2021-10-23T15:56:27.782Z"
    },
    "token": "theJWTtoken"
}

Expected Response :

{
    "administrator": {
        "id": 1,
        "full_name": "Kevin Jayden Wivano",
        "username": "kevin"
    },
    "token": "theJWTtoken"
}
1

There are 1 best solutions below

0
Nishank Gupta On

Try the below:

    render json: {:administrator => AdministratorSerializer.new(@administrator).to_h}

In place Of:

    render json: { administrator: @administrator, token: token }