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

如何修复Rails中错误生成的Candidate::Test脚手架?

解决Rails命名空间脚手架的局部视图命名错误问题

执行bin/rails generate scaffold Candidate::Test后运行rails test,出现找不到candidate/tests/_test局部视图的错误,提示存在candidate/tests/candidate_test——这是Rails生成器处理带命名空间的模型时的命名bug:生成器把局部视图命名为_candidate_test.html.erb,但控制器视图逻辑默认寻找_test.html.erb,导致路径不匹配。

修复步骤:

  • 重命名局部视图文件
    将app/views/candidate/tests/_candidate_test.html.erb重命名为app/views/candidate/tests/_test.html.erb

  • 修正视图中的引用
    检查app/views/candidate/tests下的所有视图文件(如index.html.erb、show.html.erb),把所有引用candidate_test的地方改成test:

    • 把<%= render @candidate_tests %>改为<%= render @tests %>
    • 把<%= render 'candidate_test' %>改为<%= render 'test' %>
  • 修正控制器实例变量(规范优化)
    打开app/controllers/candidate/tests_controller.rb,将@candidate_test替换为@test,@candidate_tests替换为@tests,示例:

    # 修改前
    def show
      @candidate_test = Candidate::Test.find(params[:id])
    end
    # 修改后
    def show
      @test = Candidate::Test.find(params[:id])
    end
    
  • 重新运行测试
    执行rails test验证错误是否解决

提前规避方案

生成脚手架时添加--singular-resource参数,强制生成正确命名的文件和变量:

bin/rails generate scaffold Candidate::Test --singular-resource

这个参数会直接创建_test.html.erb,同时控制器和视图自动使用@test/@tests,无需事后修改。

内容的提问来源于stack exchange,提问作者benj-by

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:18:22