You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级JSONAPI::Processor后遇resource_klasses方法未定义问题求助

问题解决:JSONAPI::Processor升级后报错undefined method 'resource_klasses'

错误原因

你遇到的问题核心是误用了结果类:

  • 原代码返回的是单个GivingNumberSearchResource实例(承载搜索参数及关联结果),对应单个资源场景,应该使用JSONAPI::ResourceOperationResult
  • 你错误替换为ResourceSetOperationResult,这个类专门用于处理资源集合(多个资源实例),单个资源实例没有它所需的resource_klasses方法,因此触发序列化报错

另外需要明确:search.execute返回的是ActiveRecord对象数组,但你的GivingNumberSearchResource是包装GivingNumberSearch实例(搜索参数载体),并通过has_many :inbound_numbers关联搜索结果,所以原设计是返回单个搜索资源,而非直接返回结果集合。

解决方案

方案一:保持返回单个搜索资源(推荐,匹配原代码设计)

继续使用JSONAPI::ResourceOperationResult,确保业务逻辑正常运行:

module Api
 module V2
   class GivingNumberSearchProcessor < JSONAPI::Processor
     def create_resource
       data = params[:data]
       search = GivingNumberSearch.new(
         country: data[:attributes][:country],
         area_code: data[:attributes][:area_code]
       )
       search.execute # 需确保此方法将搜索结果赋值给search的inbound_numbers属性
       resource = GivingNumberSearchResource.new(search, context)
       # 搜索操作建议使用:ok状态,若业务确需创建语义可保留:created
       JSONAPI::ResourceOperationResult.new(:ok, resource)
     end
   end
 end
end

方案二:直接返回搜索结果的资源集合

如果业务需求改为直接返回search.execute的结果数组,需先创建对应结果的资源类,再构建资源集合:

  1. 定义结果对应的资源类:
module Api
  module V2
    class InboundNumberResource < JSONAPI::Resource
      # 根据InboundNumber模型的实际字段定义属性
      attributes :number, :available, :country_code
    end
  end
end
  1. 修改处理器代码:
module Api
 module V2
   class GivingNumberSearchProcessor < JSONAPI::Processor
     def create_resource
       data = params[:data]
       search = GivingNumberSearch.new(
         country: data[:attributes][:country],
         area_code: data[:attributes][:area_code]
       )
       results = search.execute
       # 将每个ActiveRecord对象转换为对应资源实例
       resources = results.map { |record| InboundNumberResource.new(record, context) }
       # 使用ResourceSetOperationResult并指定资源类
       JSONAPI::ResourceSetOperationResult.new(:ok, resources, resource_klass: Api::V2::InboundNumberResource)
     end
   end
 end
end

内容的提问来源于stack exchange,提问作者aarkerio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 03:08:19