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

Rails项目中namespace:games报错uninitialized constant Games求助

Rails路由与控制器命名空间问题排查:uninitialized constant Games错误

问题描述

触发错误 uninitialized constant Games,使用:games命名空间后无法访问localhost/games/hangman页面,相关代码如下:

路由代码

Rails.application.routes.draw do
  devise_for :users
  namespace :games do
    resources :hangman, only: [:index]
  end
  get 'hangman/guess', to: 'hangman#guess'
  root to: "pages#home"
end

控制器代码

class HangmanController < ApplicationController
  def index
    @secret_word = "hangman"
  end
  def guess
    secret_word = "hangman"
    incorrect_guesses = 0
    render json: { secret_word: secret_word, incorrect_guesses: incorrect_guesses }
  end
end

模型代码

class Hangman < ApplicationRecord 
  belongs_to :user 
end

页面index代码

<div id="hangman-game" data-controller="hangman"> 
  <h1>Hangman Game</h1> 
  <div> 
    <p>Secret Word: <span data-target="hangman.secretWord"></span></p> 
    <p>Incorrect Guesses: <span data-target="hangman.incorrectGuesses"></span></p> 
    <p>Guesses Remaining: <span data-target="hangman.guessesRemaining"></span></p> 
  </div> 
  <div> 
    <input type="text" data-target="hangman.guessInput" placeholder="Enter a letter"> 
    <button data-action="click->hangman#guess">Guess</button> 
  </div> 
</div>

排查与解决步骤

  • 修正控制器的命名空间与文件位置
    命名空间:games要求控制器必须嵌套在Games模块下,且文件路径对应:

    1. 创建目录app/controllers/games,将控制器文件移至该目录,文件名保持hangman_controller.rb
    2. 修改控制器代码,嵌套到Games模块:
      class Games::HangmanController < ApplicationController
        def index
          @secret_word = "hangman"
        end
      
        def guess
          secret_word = "hangman"
          incorrect_guesses = 0
          render json: { secret_word: secret_word, incorrect_guesses: incorrect_guesses }
        end
      end
      
  • 调整路由以匹配命名空间控制器
    将hangman/guess路由移入:games命名空间内,确保对应到Games::HangmanController#guess:

    Rails.application.routes.draw do
      devise_for :users
      namespace :games do
        resources :hangman, only: [:index]
        get 'hangman/guess', to: 'hangman#guess'
      end
      root to: "pages#home"
    end
    
  • 调整视图文件位置
    将原来的index视图文件移至app/views/games/hangman目录下,Rails会自动根据命名空间查找对应视图。

  • 模型无需修改
    Hangman模型属于全局常量,不需要嵌套到Games命名空间,保持现有代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:07:29