Question

I'm new to Rails and Modules/Namespaces

My Controller is namespaced like this:

module Api
  module V1
   class PostsController < ApiController

And ActiveModel::Serializers put a "Serializers" folder in my app folder, and in it, I've created post_serializer.rb containing the following code:

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :category, 
end

When I try to access the JSON response I get:

NameError at /api/v1/posts
uninitialized constant Api::V1::PostsController::PostSerializer

What is the problem here and what is the best way to Namespace my Serializers alongside my API versions?

Était-ce utile?

La solution

be aware that namespaces should match the folder structure:

# should be in app/controllers/api/v1/posts_controller.rb
module Api
  module V1
   class PostsController < ApiController

# should be in app/serializers/post_serializer.rb
class PostSerializer < ActiveModel::Serializer

when using PostSerializer without a prefix, the current namespace is assumed. if you are referencing the global namespace use ::PostSerializer

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top