这是我第一次使用active_model_serializers我一直在寻找周围的文档,并没有找到解决方案。
我遵循了所有的入门文档,但当我试图获得序列化记录时,我得到标准rails JSON而不是序列化记录。
我在SO中发现了一个类似的线程:active_model_serializers在rails-api中不工作,在这个线程中很多人说我们需要在ApplicationController中手动添加include ActionController::Serialization
。我也跟着去了,但都没用。有谁能帮我解决这个问题吗?
控制器:
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
序列化器:
class AdministratorSerializer < ActiveModel::Serializer
attributes :id, :full_name, :username
end
实际响应:
{
"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"
}
预期响应:
{
"administrator": {
"id": 1,
"full_name": "Kevin Jayden Wivano",
"username": "kevin"
},
"token": "theJWTtoken"
}
尝试如下:
render json: {:administrator => AdministratorSerializer.new(@administrator).to_h}
In place:
render json: { administrator: @administrator, token: token }