Open vestedpr-dev opened 5 years ago
Related: "Fix for has_one relationships where related record does not exist" https://github.com/cerebris/jsonapi-resources/pull/987
Note also, this exception is when you have caching
enabled for the resource. Without caching you still get an exception, of a different (less confusing but, still confusing) form:
KeyError (key not found: 2329):
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1354:in `fetch'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1354:in `block (3 levels) in preload_included_fragments'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1349:in `each'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1349:in `each_with_index'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1349:in `block (2 levels) in preload_included_fragments'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1347:in `each'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1347:in `block in preload_included_fragments'
jsonapi-resources (0.9.10) lib/jsonapi/resource.rb:1259:in `each'
Thank you for PunditResources, we are using it heavily and it mostly works great!
When using PunditResources, one of the dangers is that the resource scope, does not match the policy scope. JSONAPI::Resources is quite a complicated beast but, what seems to happen is that, it gets the list of resources to be serialized from one place, but when it actually retrieves the resources to be serialized into the response, then it calls through the Pundit Scope (e.g. the index). (Anyone who knows, please correct me with a more sophisticated account of what JSONAPI::Resources is doing!)
When this problem occurs it throws an obscure exception:
This exception is so unrelated to the actual cause of the problem, it took me a long time to understand what was wrong. The root of this exception, I believe, is that the Pundit policy scope, when viewed by a particular user, does not match the underlying rails association.
Anyways I created this monkeypatch for our codebase so that in the future it will be more clear what's happening:
config/initializers/monkeypatch_jsonapi_resources_add_pundit_resources_exception.rb