简体   繁体   中英

uninitialized constant API::V1::ApplicationSerializer

I'm started using gem 'active_model_serializers', '~> 0.10.0' . Following this document for the implementation.

I have the following relations.

landmark has_many concerns
concern belongs_to landmark
concern has_many comments 

I have created a ApplicationSerializer at app/serializers/api/application_serializer.rb

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

My concern_serializer contains:

# ===> 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

In the above code if I replace ApplicationSerializer with ActiveModel::Serializer it works fine but I lose the common code defined in ApplicationSerializer .

Looks like an autoloading issue. ApplicationSerializer should be in its own file <serializers directory>/api/application_serializer.rb (make sure to restart server/spring after creating directories in app so that they are picked up by the autoloader)

Also you can refer to it using absolute class name: ::API::ApplicationSerializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM