ElMassimo / ElMassimo/oj_serializers
Serialization issues for self referencing models
- Dominant language
- Ruby
- Stars
- 166
- Forks
- 9
- Avg merge
- 6h 20m
- Merged PRs (30d)
- 2
Description
Hey Maximo,
I'm seeing a strange bug when using a self referencing model:
```ruby
# 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
end
```
A snippet of CommentSerializer looks like this:
```ruby
# 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
end
```
When using the same serializer here we end up with the parent comment and the reply both having the same attributes:
```json
[
{
"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:
```ruby
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
end
```
Or you can manually define the attributes like so:
```ruby
attribute :body do
comment.body
end
```
I'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 :)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.