2015-10-26 91 views
3

我想在Rails引擎使用JSONAPI Resources,我已经在doki_core定义在doki_core /应用/型号/ tenant.rb DokiCore::Tenant(模型)和DokiCore::TenantResource /应用/资源/ tenant_resource.rb。当我试图序列哈希,我遇到以下错误:JSONAPI资源:序列化名称空间的模型

NoMethodError: undefined method tenant_path' for #<Module:0x007f9d04208778> from /Users/typeoneerror/.rvm/gems/[email protected]/gems/jsonapi-resources-0.6.1/lib/jsonapi/link_builder.rb:77:in public_send'

资源使用model_name让它知道在哪里的模式实际上是:

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

我试图输出哈希对于像这样的租户:

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

这是发生错误的地方。

我怎样才能让链接正常工作和/或禁用它们?我假设这是在那里它将URL添加到资源中作为链接在输出的json中的“链接”键下。

回答

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

另一种简单的序列化您的命名空间的数据是通过使用jsonapi-utils宝石。你只需要做这样的事情:

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

宝石是基于JSON API资源,带来了Rails的方式来获得与JSON API的规范序列数据。

相关问题