Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ActiveModel::Serializers::JSON#from_json compatible with #assign_attributes #51781

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Commits on May 16, 2024

  1. Make ActiveModel::Serializers::JSON#from_json compatible with `#ass…

    …ign_attributes`
    
    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 from
    `ActiveModel::AttributeAssignment` have `#attributes=` [automatically
    aliased to `#assign_attributes`][alias].
    
    This has two unintended side effects:
    
    1. calls to `#from_json` will never invoke `#assign_attributes`
       overrides, since they invoke `#attributes=` directly
    
    2. overrides to `#assign_attributes` won't have any effects on
       `#attributes=`, since that alias is defined on the original
       implementation
    
    This commit attempts to remedy that issue by attempting to call
    `#assign_attributes` first before falling back to `#attributes=`.
    
    A change-free solution would be to encourage (through documentation) a
    corresponding `alias :attributes= assign_attributes` line any time
    models override `assign_attributes`.
    
    [ActiveModel::AttributeAssignment]: https://edgeapi.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html
    [ActiveModel::API]: https://edgeapi.rubyonrails.org/classes/ActiveModel/API.html
    [ActiveModel::Serializers::JSON#from_json]: https://edgeapi.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-from_json
    [alias]: https://github.com/rails/rails/blob/be0cb4e8f9aa0b105ddd035061202a5d23491b5a/activemodel/lib/active_model/attribute_assignment.rb#L37
    seanpdoyle committed May 16, 2024
    Configuration menu
    Copy the full SHA
    01c6cda View commit details
    Browse the repository at this point in the history