JsonApiClient / json_api_client

Build client libraries compliant with specification defined by jsonapi.org
MIT License
362 stars 186 forks source link

Pull request #386 introduced an issue on serialization #390

Open sebasjimenez10 opened 3 years ago

sebasjimenez10 commented 3 years ago

Looking at https://github.com/JsonApiClient/json_api_client/pull/386/files, I see that there's shift towards using HashWithIndiferentAccess, however, this change causes a wrong serialization when calling as_json_api. Which is causing a lot of tests to break on my end. Here's an example:

The previous symbolize_keys approach would serialize like this:

resource.as_json_api
{"type"=>"resources", "relationships"=>{"location"=>{"data"=>{"type"=>"locations", "id"=>"1"}}}, "attributes"=>{"arrival-time"=>"...", "full-name"=>"a full name", "email"=>nil, "user-data"=>[{"field"=>"color", "value"=>"blue"}], "private-notes"=>nil, "guests"=>nil, "phone"=>nil}}

but with the new with_indiferent_access approach it serializes like this:

resource.as_json_api
{"type"=>"resources", "relationships"=>{"location"=>{"data"=>{"type"=>"locations", "id"=>"1"}}}, "attributes"=>{"arrival-time"=>"...", "full-name"=>"a full name", "email"=>nil, "user-data"=>[{"field"=>"color", "value"=>"blue"}], "private-notes"=>nil, "additional-guests"=>nil, "phone"=>nil, "location"=>#<Models::Location:@attributes={"type"=>"locations", "id"=>"1", "address_line_one"=>nil, "address_line_two"=>nil}>}}

It is adding location as an attribute and set it equals to the value of to_s. which is derived from using with_indiferent_access.

These results I got from getting 1.20.0 and manually reverting the symbolize keys change.

Would really appreciate any guidance here, although it seems that the version 1.19.0 added some unexpected behavior.

Thanks in advance for any help/comments

sebasjimenez10 commented 3 years ago

Here's an update.

When you do:

SomeResource.new(some_relationship: instance_of_that_relationship)

internally, it takes the relationship as an attribute instead of as a relationship.

This alternative seems to fix the issue:

SomeResource.new.tap do |r|
  r.some_relationship = instance_of_that_relationship
end

it is definitely weird, that it would take the relationships passed in .new as attributes, but seems consistent with the .with_indifferent_access change.