3

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.

4

2 回答 2

4

整理了这个。如果您的路由以任何方式命名空间,则您的资源也需要命名空间以匹配。我的路线看起来像:

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

所以资源需要以相同的方式命名:

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);
于 2015-10-27T16:57:10.470 回答
3

序列化命名空间数据的另一种简单方法是使用jsonapi-utils gem。您只需要执行以下操作:

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

gem 基于 JSON API 资源,提供了一种 Rails 方法来使用 JSON API 的规范序列化数据。

于 2015-12-28T17:31:19.777 回答