timpone
timpone

Reputation: 19929

ActiveModel::Serializer not allowing me to load serializer in app/serializers

I have the following api controller in ('app/controllers/api/v1/companies_controller.rb'):

class Api::V1::CompaniesController < ApplicationController
  def index
    companies = Company.all
    render json: companies, serializer: CompanySerializer
  end
end

but the above is looking for Api::V1::CompanySerializer in app/serializers/api/v1/company_serializer.rb. I'd rather just have a generic company serializer in app/serializers/company_serializer. I have tried using the scope resolution operator like:

render json: companies, serializer: ::CompanySerializer

but still getting an error. How would I tell my controller to use the default serializer explicitly? I have seen this issue https://github.com/rails-api/active_model_serializers/issues/1701 and, if this is the ONLY behavior allowed, it seems like a strange choice

enter image description here

Upvotes: 2

Views: 1028

Answers (1)

Wasif Hossain
Wasif Hossain

Reputation: 3940

AMS 0.10.7 Implicit Serializer vs Explicit Serializer

You really don't need to pass any serializer option as long as your serializer has the default name. So render json: companies should work.

Explicit way would look like:

render json: companies,
  serializer: CollectionSerializer,
  each_serializer: CompanySerializer

Note: The default serializer for collections is CollectionSerializer. In your example, you tried to pass CompanySerializer to serializer.

Upvotes: 1

Related Questions