rails:active model serializer查找错误的序列化程序

时间:2014-05-01 18:50:50

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

当我调用create方法时,我得到一个nameError。

Failure/Error: post :create, { user: { email: 'charles@example.com',
     NameError:
       uninitialized constant API::V1::UsersController::UserV1Serializer

为什么将UsersController模块添加到它要查找的类中?在我的会话控制器中,我使用相同的渲染线,它不会抱怨。到底是怎么回事?

应用程序/控制器/ API / V1 / users_controller.rb

class API::V1::UsersController < API::V1::BaseController
    ...
    ...
    def create
        user = User.new(user_params)
        if user.save
          sign_in :user, user, store: false
        end
        render json: user, serializer: UserV1Serializer, root: 'user'
      end

应用程序/串行器/ API / V1 / user_v1_serializer.rb

class API::V1::UserV1Serializer < ActiveModel::Serializer
  attributes :id, :email

  def attributes
    hash = super
    if scope == object
      hash[:token] = object.authentication_token
    end
    hash
  end
end

1 个答案:

答案 0 :(得分:4)

您需要指定完整的命名空间类名UserV1Serializer,而不是指定API::V1::UserV1Serializer

如果您只是指定UserV1Serializer,它会在当前控制器API::V1::UsersController::UserV1Serializer中查找序列化程序类,这就是您收到错误的原因

uninitialized constant API::V1::UsersController::UserV1Serializer

请改用:

render json: user, serializer: API::V1::UserV1Serializer, root: 'user'