-
Notifications
You must be signed in to change notification settings - Fork 8
Open
Description
Hey Maximo,
I'm seeing a strange bug when using a self referencing model:
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :parent_comment, class_name: "Comment", optional: true
has_many :replies, class_name: "Comment", foreign_key: "parent_comment_id", dependent: :destroy
endA snippet of CommentSerializer looks like this:
# app/serializers/comment_serializer.rb
class CommentSerializer < BaseSerializer
attribute :type do "Comment" end
attributes(
:body,
:parent_comment_id,
)
attribute :replies, if: -> { expand.include?('replies') } do
CommentSerializer.render(comment.replies)
end
endWhen using the same serializer here we end up with the parent comment and the reply both having the same attributes:
[
{
"id": 543,
"type": "Comment",
"parent_comment_id": null,
"asset_files": [],
"replies": [
{
"id": 544,
"type": "Comment",
"parent_comment_id": 543,
"body": "Test reply"
}
],
"body": "Test reply"
}
]This can be fixed if by using a different serializer for the replies like:
class CommentSerializer < BaseSerializer
attribute :type do "Comment" end
attributes(
:body,
:parent_comment_id,
)
attribute :replies, if: -> { expand.include?('replies') } do
CommentReplySerializer.render(comment.replies)
end
end
class CommentReplySerializer < CommentSerializer
endOr you can manually define the attributes like so:
attribute :body do
comment.body
endI've been browsing the source code but am not sure why it works when defining individual attributes and not when using the attributes method.
Wondering if allowing the ability to set the instance_key would fix or if there is a simpler fix I am not seeing.
Let me know if you have any ideas :)
Metadata
Metadata
Assignees
Labels
No labels