I am working on a Rails 6 API only application using jsonapi-serializer gem.
I am using namespaces for the resources in my application, I also used namespaces for the serializer files.
So my serializer file looks like this:
module Applyportal
class ApplicantSerializer
include JSONAPI::Serializer
attributes :first_name, :middle_name, :last_name, :phone, :email, :username, :password, :nationality, :state_of_origin, :local_government
belongs_to :local_government, serializer: Personalinfo::LocalGovernment
belongs_to :marital_status, serializer: Personalinfo::MaritalStatus
belongs_to :nationality, serializer: Personalinfo::Nationality
has_many :applications, serializer: Applyportal::Application
cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 1.hour
end
end
But when I try to make a Post request to this resource I get the error below:
NoMethodError (undefined method `record_type' for #<Class:0x00007f05d4d451f8>
Did you mean? record_timestamps)
I can't seem to figure out what the issue is.
The issue was coming from how I defined my serializer associations
Here's how I solved it:
So I used namespaces for the resources in my application, I also used namespaces for the serializer files.
So my serializer file looked like this:
module Applyportal
class ApplicantSerializer
include JSONAPI::Serializer
attributes :first_name, :middle_name, :last_name, :phone, :email, :username, :password, :nationality, :state_of_origin, :local_government
belongs_to :local_government, serializer: Personalinfo::LocalGovernment
belongs_to :marital_status, serializer: Personalinfo::MaritalStatus
belongs_to :nationality, serializer: Personalinfo::Nationality
has_many :applications, serializer: Applyportal::Application
cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 1.hour
end
end
I was missing to add Serializer
at the end of each association which was making it difficult for the rails application to find the record_type
, so instead of:
belongs_to :local_government, serializer: Personalinfo::LocalGovernment
it should be
belongs_to :local_government, serializer: Personalinfo::LocalGovernmentSerializer
So my serializer file looked like this afterwards:
module Applyportal
class ApplicantSerializer
include JSONAPI::Serializer
attributes :first_name, :middle_name, :last_name, :phone, :email, :username, :password, :nationality, :state_of_origin, :local_government
belongs_to :local_government, serializer: Personalinfo::LocalGovernmentSerializer
belongs_to :marital_status, serializer: Personalinfo::MaritalStatusSerializer
belongs_to :nationality, serializer: Personalinfo::NationalitySerializer
has_many :applications, serializer: Applyportal::ApplicationSerializer
cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 1.hour
end
end
That's all.
I hope this helps