Question

When I call the the create method i get a nameError.

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

why is it adding that UsersController module to the class it is looking for? In my sessions controller I use the same exact render line and it doesn't complain. what is going on?

app/controllers/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

app/serializers/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
Was it helpful?

Solution

Instead of specifying UserV1Serializer, you need to specify the full namespaced class name API::V1::UserV1Serializer.

If you just specify the UserV1Serializer, its looking for the serializer class within current controller API::V1::UsersController::UserV1Serializer which is why you get an error as

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

Use this instead:

render json: user, serializer: API::V1::UserV1Serializer, root: 'user'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top