【问题标题】:active model serializer not working with rails-api gem活动模型序列化程序不适用于 rails-api gem
【发布时间】:2015-01-01 03:41:10
【问题描述】:

我在我的项目中为 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 字段。

好像它没有使用序列化器。

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

谢谢

【问题讨论】:

  • 把这个改成class Api::MessagesController &lt; Api::BaseController改成class Api::MessagesController &lt; ApplicationController,改成也渲染json:@messages,试一次
  • 不,不好。 Api::BaseController 类继承 ApplicaionController 类。所以基本上是一样的。

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


【解决方案1】:

在您的 BaseController 中,您是否添加了下面的包含?

include ActionController::Serialization

【讨论】:

  • 这是正确的解决方案。永远不要降级 gem。
【解决方案2】:

您使用的是什么版本的 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

【讨论】:

  • 谢谢!在意识到这一点之前会浪费几个小时!
【解决方案3】:

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

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

【讨论】:

  • 这对我来说没有任何改变。还有其他想法吗?
【解决方案4】:

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

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

它很丑,但它对我有用。

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

def attachments
  attachments = object.attachments.to_a
  return [] if attachments.empty?
  serializer = ActiveModel::Serializer::ArraySerializer.new(attachments, each_serializer:AttachmentSerializer)
  ActiveModel::Serializer::Adapter::JsonApi.new(serializer).as_json[:attachments]
end

【讨论】:

    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多