Skip to content

Polymorphic hash does not select the proper serializer for included records #30

@christophersansone

Description

@christophersansone

While reviewing the code and implementing #29, I noticed that there are no tests for specifying polymorphic as a hash, and I can't seem to find any code to support the implementation.

This is the code for determining the serializer for a specific record within a relationship (from here):

if relationship_item.polymorphic.is_a?(Hash)
  record_type = inc_obj.class.name.demodulize.underscore
  serializer = self.compute_serializer_name(inc_obj.class.name.demodulize.to_sym).to_s.constantize
end

And compute_serializer_name is not referencing it at all either:

def compute_serializer_name(serializer_key)
  return serializer_key unless serializer_key.is_a? Symbol
  namespace = self.name.gsub(/()?\w+Serializer$/, '')
  serializer_name = serializer_key.to_s.classify + 'Serializer'
  (namespace + serializer_name).to_sym
end

It looks like the polymorphic hash "works" when writing the relationships type/id hash. It will compare the record with the classes specified in the hash, and then output the value of the key as the type. However, when including records, it selects the serializer based on the record's class name... which is how the relationships work when polymorphic is simply set to true. Therefore, if someone had a reason to specify polymorphic as a hash, and they are including records, then the types will likely mismatch.

Personally, I think that polymorphic: true is helpful in the typically simple cases: it infers the type and serializer from the name of the relationship. However, I think we can design a better API for determining the correct type and serializer for polymorphic relationships and other occasions where they are not constant. I think #29 is a better approach to solving this problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions