【问题标题】:ActiveModel::Serializer not being called when rendering json?渲染 json 时没有调用 ActiveModel::Serializer?
【发布时间】:2014-01-15 17:06:17
【问题描述】:

我正在尝试在 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 缺少什么。

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢,我遇到了 4.1.7 的问题,ActionController::API.send(:include, ActionController::Serialization) 完成了这项工作。
    【解决方案2】:

    包括 ActionController::序列化

    在应用控制器中

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2017-09-28
      相关资源
      最近更新 更多