Reputation: 2224
The serializer for Article
has two nested serializers: Author
and Chapter
. The latter two also have their own individual serializers. I'm using the active_model_serializer gem.
# The nested serializer
class Api::V1::ArticleSerializer < Api::V1::SerializerWithSessionMetadata
attributes :id, ...
has_many :authors, root: :authors_attributes
has_many :chapters, through: :authors, root: :chapters_attributes
class Api::V1::AuthorSerializer < ActiveModel::Serializer
...
end
class Api::V1::ChapterSerializer < ActiveModel::Serializer
...
end
end
# The two individual serializers
class Api::V1::AuthorSerializer < Api::V1::SerializerWithSessionMetadata
...
end
class Api::V1::ChapterSerializer < Api::V1::SerializerWithSessionMetadata
...
end
Problem: I currently sometimes get an error while other times I don't (while making the same server request). If the error happens, I restart the server, make the same request, and the error isn't there.
superclass mismatch for class ArticleSerializer
The error refers to class Api::V1::AuthorSerializer < ActiveModel::Serializer
in the nested serializer. It seems to particularly happen when creating a new author
record. This uses:
author = @article.authors.build(create_params)
if author.save
render json: @article, status: :created
end
So this method's render
line calls on the nested serializer after created an author. What could be the cause of this behavior?
Is the line class Api::V1::AuthorSerializer < ActiveModel::Serializer
correct or should it perhaps inherit from something else? Perhaps it sees the Author
s nested serializer higher in hierarchy because it inherits from a higher serializer than its individual serializer does. And as a result uses the nested version when it should use its individual version.
If I let the nested version inherit from Api::V1::SerializerWithSessionMetadata
instead, then the error is gone. However, the disadvantage then is that it repeats the attributes from the meta serializer for each individual author and chapter in the article serializer.
Upvotes: 2
Views: 445
Reputation: 1074
My guess is that problem is in namespace for nested serializer. When you create a class within other one, actually, you create a class inside other one's namespace. And inner class doesn't inherit anything from outer one except its name. So your inner AuthorSerializer can be called as Api::V1::ArticleSerializer::Api::V1::AuthorSerializer
So try to rename your classes
class Api::V1::ArticleSerializer < Api::V1::SerializerWithSessionMetadata
...
class AuthorSerializer < ActiveModel::Serializer
...
end
class ChapterSerializer < ActiveModel::Serializer
...
end
end
# The two individual serializers
class Api::V1::AuthorSerializer < Api::V1::SerializerWithSessionMetadata
...
end
class Api::V1::ChapterSerializer < Api::V1::SerializerWithSessionMetadata
...
end
Upvotes: 1