Skip to content

Commit faf66b6

Browse files
authored
Merge pull request #905 from austenito/fix-context-for-cached-resources
Fix issue where resources received context nested in hash
2 parents cae9b41 + 0936916 commit faf66b6

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

lib/jsonapi/resource.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1040,7 +1040,7 @@ def cached_resources_for(records, serializer, options)
10401040
cache_ids = pluck_arel_attributes(records, t[_primary_key], t[_cache_field])
10411041
resources = CachedResourceFragment.fetch_fragments(self, serializer, options[:context], cache_ids)
10421042
else
1043-
resources = resources_for(records, options).map{|r| [r.id, r] }.to_h
1043+
resources = resources_for(records, options[:context]).map{|r| [r.id, r] }.to_h
10441044
end
10451045

10461046
preload_included_fragments(resources, records, serializer, options)

test/controllers/controller_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2451,6 +2451,12 @@ def test_destroy_relationship_has_and_belongs_to_many_refect
24512451
ensure
24522452
JSONAPI.configuration.use_relationship_reflection = false
24532453
end
2454+
2455+
def test_index_with_caching_enabled_uses_context
2456+
assert_cacheable_get :index
2457+
assert_response :success
2458+
assert json_response['data'][0]['attributes']['title'] = 'Title'
2459+
end
24542460
end
24552461

24562462
class Api::V5::AuthorsControllerTest < ActionController::TestCase

test/fixtures/active_record.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,9 @@ class BoatsController < JSONAPI::ResourceController
717717
end
718718

719719
class BooksController < JSONAPI::ResourceController
720+
def context
721+
{ title: 'Title' }
722+
end
720723
end
721724

722725
### CONTROLLERS
@@ -1246,7 +1249,13 @@ class AuthorResource < JSONAPI::Resource
12461249
end
12471250

12481251
class BookResource < JSONAPI::Resource
1252+
attribute :title
1253+
12491254
has_many :authors, class_name: 'Author', inverse_relationship: :books
1255+
1256+
def title
1257+
context[:title]
1258+
end
12501259
end
12511260

12521261
class AuthorDetailResource < JSONAPI::Resource

0 commit comments

Comments
 (0)