ActiveModel::Serializers Gem - Versioned API Namespacing Issue

邮差的信 提交于 2019-12-06 10:14:46

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/15463356/activemodelserializers-gem-versioned-api-namespacing-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!