【发布时间】: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