Search code examples
ruby-on-railsrubyjson-apijsonapi-resources

JSONAPI resources: serialize a namespaced model


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.


Solution

  • 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);