【问题标题】:JSONAPI resources: serialize a namespaced modelJSONAPI 资源:序列化命名空间模型
【发布时间】:2016-01-26 04:17:19
【问题描述】:

我正在尝试在 Rails 引擎中使用JSONAPI Resources,我在 doki_core/app/models/tenant.rb 和 doki_core/app/resources/tenant_resource 中定义了DokiCore::Tenant(模型)和DokiCore::TenantResource .rb。当我尝试序列化为哈希时,遇到以下错误:

NoMethodError: 未定义方法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'

资源使用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 中“链接”键下的链接。

【问题讨论】:

    标签: ruby-on-rails ruby json-api jsonapi-resources


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      序列化命名空间数据的另一种简单方法是使用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 规范序列化的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-16
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多