Allow relationship ID to be overwritten for belongs_to relationships #2128
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Purpose
If the
id
attribute for a class isn't taken directly from the object when serializing it, it may be desirable for other classes that serialize a relationship with that class to overwrite the relationship IDs they serialize.For example, suppose we have:
In the above example, serializing a list of
Repo
s will give thegithub_id
for each one, but serializing aConfig
will give theid
for its parent repo.Changes
I've updated the
belongs_to?
path ofRelationship#data_for_one
to useread_attribute_for_serialization
instead ofobject.send
to fetch the serialized foreign key. This allows the serialized relationship ID to beoverwritten using:
Caveats
Ideally AMS would inspect the
RepoSerializer
when serializing theConfig
, and realise it can't just output the foreign key. Unfortunately, getting the serialization class for the child repo currently requires loading the record (via evaluatinglazy_assocation
), and loses the performance benefit of the existingbelongs_to?
path.Related GitHub issues
#2125. (Not resolved by this, but the ID issue is at least improved, for no performance cost.)
Additional helpful information