3

我正在尝试在 Rails 4.0.0 中使用 active_model_serializers 来序列化我的 json 响应。但是,当我使用 AMS 类时,似乎根本没有被调用/使用

render json: user

我不确定是否存在一些配置问题,或者我是否错误地使用了命名空间。

Gemfile 有:

gem 'active_model_serializers', '0.8.0'

控制器(在 app/controllers/api/v1/users_controller.rb 中):

module API
  module V1
    class UsersController < API::V1::BaseController
      def show
        user = User.find(params[:id])
        render json: user
      end
    end
  end
end

UserSerializer(在 app/serializers/user_serializer.rb 中)

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name
end

但在 json 响应中,我仍然看到完整的对象,即

{"id":1,"first_name":"Test","last_name":"User1","created_at":"2013-12-26T07:12:02.618Z","updated_at":"2013-12-26T07:12:02.618Z"}

我已经尝试了从显式调用render json: user, serializer: UserSerializer到将序列化程序命名空间到 API::V1 的所有方法,结果是一样的。我在这里错过了什么吗?

编辑BaseController:这是通过让我继承ActionController::Base而不是修复的ActionController::Metal。不过,不完全确定缺少什么ActionController::Metal

4

2 回答 2

1

我在 Rails3 上遇到了类似的问题,我不得不将此行添加到应用初始化程序文件夹中

ActionController::API.send(:include, ActionController::Serialization)

检查你是否需要做类似的事情,比如

ActionController:: Metal.send(:include, ActionController::Serialization)
于 2014-09-01T14:15:44.490 回答
1

包括 ActionController::序列化

在应用程序控制器中

于 2016-02-26T07:20:26.987 回答