JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Polymorphic code in serializer makes some AR assumptions

Open
#829 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
2.3k
Forks
546
PR merge metrics
No merged PRs in 30d

Description

In the following code in resource_serializer.rb


    def foreign_key_types_and_values(source, relationship)
      if relationship.is_a?(JSONAPI::Relationship::ToMany)
        if relationship.polymorphic?
          assoc = source._model.public_send(relationship.name)
          # Avoid hitting the database again for values already pre-loaded
          if assoc.respond_to?(:loaded?) and assoc.loaded?
            assoc.map do |obj|
              [obj.type.underscore.pluralize, @id_formatter.format(obj.id)]
            end
          else
            assoc.pluck(:type, :id).map do |type, id|
              [type.underscore.pluralize, @id_formatter.format(id)]
            end
          end
        else
          source.public_send(relationship.name).map do |value|
            [relationship.type, @id_formatter.format(value.id)]
          end
        end
      end
    end

It makes the assumption that if you specify a polymorphic relationship that it should get the data straight from the model rather than allowing this to be changed via the resource.
It also assumes that we are using "id" and "type" which is very much an active record thing.

In my application, I am using active record, but have a "has_many" relationship to a class which then has a has_many polymorphic. I effectively want to do a has_many through the middle class straight to the polymorphic data which I cannot find a way of doing.

If the above code allowed the resource to intervene here, I could have overriden something.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in resource_serializer.rb at foreign_key_types_and_values and trace how polymorphic relationships obtain their values. Identify the resource-level extension point needed to avoid the Active Record id/type assumptions, then verify that a resource can supply a has-many-through polymorphic relationship without the serializer querying the model directly.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
api, backend
Issue type
Refactor
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.