【问题标题】:Ruby On Rails 4 - Serializers not calledRuby On Rails 4 - 未调用序列化程序
【发布时间】:2016-07-14 22:32:37
【问题描述】:

我正在使用 Ruby-On-Rails 4 构建 JSON API。

为了序列化我的 JSON 响应,我使用了 active_model_serializers 版本 0.9.4。

我有一个继承自 ApplicationController 的 ApiController。我所有的控制器都继承自 ApiController。

下面是 ApiController 的样子:

class Api::ApiController < ApplicationController
  include ActionController::Serialization
  private

    def respond_with_json(payload)
      render json: payload, root: false, status: 200
    end
end

我使用rails g serializer friendship 创建了一个与友谊模型关联的 FriendshipSerializer。这生成了以下文件:

class FriendshipSerializer < ActiveModel::Serializer
  attributes :id, :image
end

这里是friendships#index控制器动作的代码:

def index
  friendships = current_user.friendships.order(created_at: "DESC")
  respond_with_json(friendships)
end

我目前遇到的问题是在调用friendships#index 控制器操作时,它返回一个包含所有友谊模型数据的 JSON 数组,而它应该只返回 ids(根据 FriendshipSerializer)。

【问题讨论】:

  • 哪个版本的active_model_serializers?
  • 我正在使用“0.9.4”
  • 如果你指定了序列化器会发生什么? github.com/rails-api/active_model_serializers/tree/…
  • 当我指定一个序列化器时,它工作正常。问题是我不想这样做,因为这不是一个好习惯
  • 你说得对,这是一个已知问题(序列化程序的自动加载在某些情况下不起作用)

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


【解决方案1】:

我注意到您的问题中有一些拼写不一致的地方。您确定模型和序列化程序的类名匹配吗?例如,如果您的模型类名为“Friendship”,AMS 将查找名为“FriendshipSerializer”的序列化程序。如果 AMS 没有找到该序列化程序,我相信它仍然会独立于序列化程序呈现记录的属性;所以如果你有一个“Friendship”模型和“FrienshipSerializer”(反之亦然),这可能就是问题所在。

【讨论】:

  • 我没有从我的项目代码中复制粘贴。我自己编写了整个代码...我检查了我的 ruby​​ 代码,一切正常
【解决方案2】:

由于它在序列化程序为 explicitly specified 时工作,我怀疑这是一个已知问题(在某些情况下自动加载序列化程序不起作用,这可能是也可能不是错误,因为这可能是由其他 gem 的干扰引起的) .如果您可以忍受这个(或找到解决方法),您可以继续使用 0.9(它更“经过实战测试”),否则尝试使用当前版本 0.10。请注意,这些版本之间存在一些重大变化。

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 2023-03-29
    • 2010-10-10
    • 2010-10-11
    • 1970-01-01
    • 2014-12-10
    • 2012-01-28
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多