4

I'm trying to use JSONAPI Resources in a Rails engine and I've defined DokiCore::Tenant (the model) in doki_core/app/models/tenant.rb and DokiCore::TenantResource in doki_core/app/resources/tenant_resource.rb. When I attempt to serialize to hash, I encounter the following error:

NoMethodError: undefined method tenant_path' for #<Module:0x007f9d04208778> from /Users/typeoneerror/.rvm/gems/ruby-2.2.2@doki/gems/jsonapi-resources-0.6.1/lib/jsonapi/link_builder.rb:77:inpublic_send'

The resource uses model_name to let it know where the model actually is:

module DokiCore
  class TenantResource < JSONAPI::Resource
    model_name 'DokiCore::Tenant'
    # ...
  end
end

I'm trying to output the hash for a tenant like so:

tenant = DokiCore::Tenant.find(1); 
resource = DokiCore::TenantResource.new(tenant, nil); 
serializer = JSONAPI::ResourceSerializer.new(DokiCore::TenantResource); 
serializer.serialize_to_hash(resource);

which is where the error happens.

How can I get the links to work correctly and/or disable them? I assume this is there it adds the URL to the resource as a link under the "links" key in the outputted json.

typeoneerror
  • 55,990
  • 32
  • 132
  • 223

2 Answers2

4

Sorted this out. If your routes are namespaced in any way, your resources also need to be namespaced to match. My routes look something like:

namespace :api do
  namespace :v1 do
    resources :tenants
  end
end

So the resource needs to be namespaced the same way:

tenant = DokiCore::Tenant.find(1); 
resource = DokiCore::API::V1::TenantResource.new(tenant, nil); 
serializer = JSONAPI::ResourceSerializer.new(DokiCore::API::V1::TenantResource); 
serializer.serialize_to_hash(resource);
typeoneerror
  • 55,990
  • 32
  • 132
  • 223
3

Another simple way to serialize your namespaced data is by using the jsonapi-utils gem. You will just need to do something like this:

class API::V1::UsersController < API::V1::BaseController
  def index
    jsonapi_render json: User.all
  end
end

The gem is based on JSON API Resources, bringing a Rails way to get data serialized with JSON API's specs.

Tiago G.
  • 119
  • 2
  • 3