Make ActiveModel::Serializers::JSON#from_json
compatible with #assign_attributes
#51781
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.
Motivation / Background
Prior to this commit, models that inherit from
ActiveModel::AttributeAssignment (either directly or through including ActiveModel::API) lose their ability to override the attribute assignment utilized during calls to
ActiveModel::Serializers::JSON#from_json.
Incidentally,
#from_json
calls#attributes=
(instead of#assign_attributes
), whereas models that inherit fromActiveModel::AttributeAssignment
have#attributes=
automatically aliased to#assign_attributes
.This has two unintended side effects:
calls to
#from_json
will never invoke#assign_attributes
overrides, since they invoke#attributes=
directlyoverrides to
#assign_attributes
won't have any effects on#attributes=
, since that alias is defined on the original implementationDetail
This commit attempts to remedy that issue by attempting to call
#assign_attributes
first before falling back to#attributes=
.Additional information
A change-free solution would be to encourage (through documentation) a corresponding
alias :attributes= assign_attributes
line any time models overrideassign_attributes
.Alternatively, the
ActiveModel::AttributeAssignment#assign_attributes
method could be defined as#attributes=
instead (with a complementaryalias assign_attributes attributes=
call). This is likely a backwards-incompatible change.Checklist
Before submitting the PR make sure the following are checked:
[Fix #issue-number]