JSONAPI 资源:序列化命名空间模型
JSONAPI resources: serialize a namespaced model
我正在尝试在 Rails 引擎中使用 JSONAPI Resources,并且我已经在 doki_core/app/models/tenant.rb 和 [=13] 中定义了 DokiCore::Tenant
(模型) =] 在 doki_core/app/resources/tenant_resource.rb。当我尝试序列化为散列时,遇到以下错误:
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: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);
这是错误发生的地方。
如何让 link 正常工作 and/or 禁用它们?我假设这是它在输出的 json.
中的 "links" 键下将 URL 作为 link 添加到资源中
解决了这个问题。如果您的路由以任何方式命名空间,您的资源也需要命名空间以匹配。我的路线看起来像:
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);
序列化命名空间数据的另一种简单方法是使用 jsonapi-utils gem。你只需要做这样的事情:
class API::V1::UsersController < API::V1::BaseController
def index
jsonapi_render json: User.all
end
end
gem基于JSONAPI资源,带来了Rails获取数据序列化方式JSONAPI'规格。
我正在尝试在 Rails 引擎中使用 JSONAPI Resources,并且我已经在 doki_core/app/models/tenant.rb 和 [=13] 中定义了 DokiCore::Tenant
(模型) =] 在 doki_core/app/resources/tenant_resource.rb。当我尝试序列化为散列时,遇到以下错误:
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: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);
这是错误发生的地方。
如何让 link 正常工作 and/or 禁用它们?我假设这是它在输出的 json.
中的 "links" 键下将 URL 作为 link 添加到资源中解决了这个问题。如果您的路由以任何方式命名空间,您的资源也需要命名空间以匹配。我的路线看起来像:
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);
序列化命名空间数据的另一种简单方法是使用 jsonapi-utils gem。你只需要做这样的事情:
class API::V1::UsersController < API::V1::BaseController
def index
jsonapi_render json: User.all
end
end
gem基于JSONAPI资源,带来了Rails获取数据序列化方式JSONAPI'规格。