Skip to content

Serialization issues for self referencing models #35

@kengreeff

Description

@kengreeff

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
end

A 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
end

When 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
end

Or you can manually define the attributes like so:

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 :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions