ActiveModel::Serializers Gem - 版本化 API 命名空间问题 [英] ActiveModel::Serializers Gem - Versioned API Namespacing Issue

查看:51
本文介绍了ActiveModel::Serializers Gem - 版本化 API 命名空间问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 和模块/命名空间的新手

I'm new to Rails and Modules/Namespaces

我的控制器命名空间如下:

My Controller is namespaced like this:

module Api
  module V1
   class PostsController < ApiController

并且 ActiveModel::Serializers 在我的应用程序文件夹中放置了一个Serializers"文件夹,我在其中创建了包含以下代码的 post_serializer.rb:

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

当我尝试访问 JSON 响应时,我得到:

When I try to access the JSON response I get:

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

这里的问题是什么?在我的 API 版本旁边命名我的序列化程序的最佳方法是什么?

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

推荐答案

注意命名空间应该与文件夹结构相匹配:

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

当使用不带前缀的 PostSerializer 时,假定当前命名空间.如果您要引用全局命名空间,请使用 ::PostSerializer

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

这篇关于ActiveModel::Serializers Gem - 版本化 API 命名空间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆