当我调用create方法时,我得到一个nameError。
Failure/Error: post :create, { user: { email: 'charles@example.com',
NameError:
uninitialized constant API::V1::UsersController::UserV1Serializer
为什么将UsersController模块添加到它要查找的类中?在我的会话控制器中,我使用相同的渲染线,它不会抱怨。到底是怎么回事?
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
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
答案 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'