【问题标题】:uninitialized constant API::V1::ApplicationSerializer未初始化的常量 API::V1::ApplicationSerializer
【发布时间】:2020-04-12 14:58:32
【问题描述】:

我开始使用gem 'active_model_serializers', '~> 0.10.0'。关注this 文档 为实施。

我有以下关系。

landmark has_many concerns
concern belongs_to landmark
concern has_many comments 

我在app/serializers/api/application_serializer.rb 创建了一个ApplicationSerializer

module API
  class ApplicationSerializer < ActiveModel::Serializer
     # some commode here
  end
end

我的关注序列化器包含:

# ===> Does not work <=====
module API::V1
  class ConcernSerializer < ApplicationSerializer
    attributes :id, :body
    has_many :comments
    belongs_to :landmark

    class CommentSerializer < ApplicationSerializer
      attributes :id, :body
    end

    class LandmarkSerializer < ApplicationSerializer
      attributes :id, :short_address
    end

  end
end


# ====> However, this works <====
module API::V1
  class ConcernSerializer < ApplicationSerializer
    attributes :id, :body
    has_many :comments

    class CommentSerializer < ActiveModel::Serializer
      attributes :id, :body
    end

  end
end

# ===> Does not work again<=====
module API::V1
  class ConcernSerializer < ApplicationSerializer
    attributes :id, :body
    has_many :comments
    belongs_to :landmark

    class CommentSerializer < ActiveModel::Serializer
      attributes :id, :body
    end

    class LandmarkSerializer < ActiveModel::Serializer
      attributes :id, :short_address
    end

  end
end

在上面的代码中,如果我将ApplicationSerializer 替换为ActiveModel::Serializer,它可以正常工作,但我会丢失ApplicationSerializer 中定义的通用代码。

【问题讨论】:

    标签: ruby-on-rails active-model-serializers


    【解决方案1】:

    看起来像一个自动加载问题。 ApplicationSerializer 应该在它自己的文件&lt;serializers directory&gt;/api/application_serializer.rb 中(确保在app 中创建目录后重新启动服务器/spring,以便它们被自动加载器拾取)

    你也可以使用绝对类名来引用它:::API::ApplicationSerializer

    【讨论】:

    • 我已经更新了这个问题。似乎不是自动加载问题。
    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多