活动模型序列化程序不适用于 rails-api gem [英] active model serializer not working with rails-api gem
问题描述
我在我的 json api 项目中使用 rails-api gem,为此我使用活动模型序列化程序 gem 来序列化我的对象,但有些对象没有使用活动模型序列化程序进行序列化.
I am using rails-api gem in my project for json api, and for that purpose I used active model serializer gem for serializing my objects but some how the objects are not being serialized using active model serializer.
我的序列化器文件夹中有一个 MessageSerializer
I have a MessageSerializer inside of my serializers folder
class MessageSerializer < ActiveModel::Serializer
attributes :id, :sender_id, :recipient_id, :sender_type, :subj, :body, :status, :sender
def sender
object.user.try('username')
end
end
我的消息控制器如下
class Api::MessagesController < Api::BaseController
def index
@messages = current_user.incoming_messages
render json: @messages, serializer: MessageSerializer
end
end
但问题是抛出给客户端的序列化对象包含消息模型中的所有字段,即;它也包含 created_at、updated_at 字段.
But the problem is that the serialized object thrown to client contains all the fields in message model ie; it contains created_at, updated_at fields too.
好像没有使用序列化器.
Seems like its not using serializer.
可能出了什么问题?我搜索了很多,但没有找到任何对我有帮助的帖子.
What might have gone wrong? I searched a lot about it but didn't found any post that helped me.
谢谢
推荐答案
在你的 BaseController 中,你是否添加了下面的 include ?
In your BaseController, did you add the include bellow ?
包括 ActionController::Serialization
这篇关于活动模型序列化程序不适用于 rails-api gem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!