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

Rails后端GraphQL请求报错:未初始化常量Types::BaseObject

Rails GraphQL 报错:uninitialized constant Types::BaseObject

错误日志

Started POST "/graphql" for 127.0.0.1 at 2023-04-06 13:27:07 +0200
Processing by GraphqlController#execute as */*
  Parameters: {...}
Completed 500 Internal Server Error in 266ms (ActiveRecord: 0.0ms | Allocations: 3660)


NameError (uninitialized constant Types::BaseObject):

app/graphql/types/query_type.rb:2:in `<module:Types>'
app/graphql/types/query_type.rb:1:in `<main>'
...

涉及代码(QueryType)

module Types
  class QueryType < Types::BaseObject
    field :discord_user, DiscordUserType, null: true do
      argument :id, ID, required: true
    end

    def discord_user(id:)
      DiscordUser.find(id)
    end

    field :discord_users, [DiscordUserType], null: false

    def discord_users
      DiscordUser.all
    end
  end
end

问题背景

未发现命名规范问题,且BaseObject由graphql gem提供,不清楚为何触发该错误。


解决方法
  • 检查BaseObject文件是否存在
    确认app/graphql/types/base_object.rb文件是否存在,正确内容应为:

    module Types
      class BaseObject < GraphQL::Schema::Object
      end
    end
    

    若缺失,手动创建该文件——这是graphql gem初始化时默认生成的基础类,缺失会导致找不到Types::BaseObject。

  • 确认graphql gem的安装与初始化

    1. 确保Gemfile已添加gem 'graphql',并执行过bundle install。
    2. 检查是否运行过rails generate graphql:install命令,该命令会自动生成包括BaseObject在内的完整GraphQL基础文件结构。若未执行过,运行该命令(注意会覆盖已有配置,建议先备份相关文件)。
  • 验证文件加载顺序
    Rails默认会加载app/graphql下的所有文件,但如果存在自定义加载规则,可能导致BaseObject在QueryType之后加载。可在config/application.rb中明确添加加载路径:

    config.autoload_paths += %W(#{config.root}/app/graphql)
    config.autoload_paths += %W(#{config.root}/app/graphql/types)
    

    添加后重启Rails服务器。

  • 排查命名冲突
    确认项目中没有其他同名的Types模块或BaseObject类,避免命名空间冲突导致无法正确识别目标类。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:12:47