diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ba42d90..a6d0ffa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- [#353](https://github.com/JsonApiClient/json_api_client/pull/353) - fix to support deserializing resources with relationships without those related resources being included in the response (issue [#352](https://github.com/JsonApiClient/json_api_client/issues/352)). + ## 1.14.0 - [#338](https://github.com/JsonApiClient/json_api_client/pull/338) - implement hash and eql? for builder class diff --git a/lib/json_api_client/included_data.rb b/lib/json_api_client/included_data.rb index 0b7063f4..8cf689c7 100644 --- a/lib/json_api_client/included_data.rb +++ b/lib/json_api_client/included_data.rb @@ -36,9 +36,7 @@ def data_for(method_name, definition) if data.is_a?(Array) # has_many link - data.map do |link_def| - record_for(link_def) - end + data.map(&method(:record_for)).compact else # has_one link record_for(data) @@ -53,7 +51,8 @@ def has_link?(name) # should return a resource record of some type for this linked document def record_for(link_def) - data[link_def["type"]][link_def["id"]] + record = data[link_def["type"]] + record[link_def["id"]] if record end end end diff --git a/test/unit/compound_non_included_document_test.rb b/test/unit/compound_non_included_document_test.rb new file mode 100644 index 00000000..853d52e1 --- /dev/null +++ b/test/unit/compound_non_included_document_test.rb @@ -0,0 +1,63 @@ +require 'test_helper' + +class CompoundNonIncludedDocumentTest < MiniTest::Test + + TEST_DATA = %{ + { + "links": { + "self": "http://example.com/posts", + "next": "http://example.com/posts?page[offset]=2", + "last": "http://example.com/posts?page[offset]=10" + }, + "data": [{ + "type": "posts", + "id": "1", + "attributes": { + "title": "JSON API paints my bikeshed!" + }, + "relationships": { + "author": { + "links": { + "self": "http://example.com/posts/1/relationships/author", + "related": "http://example.com/posts/1/author" + }, + "data": { "type": "people", "id": "9" } + }, + "comments": { + "links": { + "self": "http://example.com/posts/1/relationships/comments", + "related": "http://example.com/posts/1/comments" + }, + "data": [ + { "type": "comments", "id": "5" }, + { "type": "comments", "id": "12" } + ] + } + }, + "links": { + "self": "http://example.com/posts/1" + } + }] + } + } + + def test_can_handle_related_data_without_included + stub_request(:get, "http://example.com/articles") + .to_return(headers: {content_type: "application/vnd.api+json"}, body: TEST_DATA) + + articles = Article.all + + assert articles.is_a?(JsonApiClient::ResultSet) + assert_equal 1, articles.length + + article = articles.first + assert_equal "1", article.id + assert_equal "JSON API paints my bikeshed!", article.title + + # has_one is nil if not included + assert_nil article.author + + # has_many is empty if not included + assert_equal 0, article.comments.size + end +end