活动模型序列化程序不使用rails-api gem

时间:2014-11-05 02:42:29

标签: ruby-on-rails active-model-serializers rails-api

我在json api的项目中使用rails-api gem,为此目的,我使用了活动模型序列化程序gem来序列化我的对象,但是一些如何使用活动模型序列化器来序列化对象。

我的序列化程序文件夹里面有一个MessageSerializer

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字段。

似乎没有使用序列化器。

可能出了什么问题? 我搜索了很多关于它但未找到任何帮助我的帖子。

由于

4 个答案:

答案 0 :(得分:15)

在您的BaseController中,您是否添加了包含以下内容?

include ActionController::Serialization

答案 1 :(得分:10)

您使用的是什么版本的AMS?

我遇到了同样的问题,并且能够通过将AMS版本从0.9.X更改为0.8.X来解决此问题。这可以通过在Gemfile中添加版本号来完成。

gem 'active_model_serializers', '~> 0.8.0'

有关AMS GitHub回购的说明。

https://github.com/rails-api/active_model_serializers#maintenance-please-read

答案 2 :(得分:5)

这是因为在rails-api中默认没有加载序列化。
你必须这样做:

class ApplicationController < ActionController::API
  include ::ActionController::Serialization
end

答案 3 :(得分:1)

我没有降级,我花了一些时间尝试不同的事情,最后我得到了这样的模式:

Fred <b>Camp</b>bell

它很丑,但它为我做了诀窍。

对于has_many关系,您可以执行以下操作:

def sender
  if object.sender
    serializer = SenderSerializer.new(object.sender)
    ActiveModel::Serializer::Adapter::JsonApi.new(serializer).as_json[:senders]
  end
end