Test:Module 的未定义方法“新" [英] undefined method `new' for Test:Module
问题描述
您好,我遇到了命名空间冲突的问题.我有一个模型:测试和控制器 TestsController.服务器显示错误
Hello I have a problem of conflict of the namespace. I have a model: Test and controller TestsController. server displays an error
undefined method `new' for Test:Module
我阅读了这个问题 rails 模型
添加到 UserTest 模块中的模型 Test
added to the model Test in module UserTest
module UserTest
class Test < ActiveRecord::Base
....
end
end
并添加到控制器
class TestsController < ApplicationController
def new
@test = UserTest::Test.new
@test.questions.build
@title = "New test"
end
...
end
服务器显示错误:未初始化的常量 TestsController::UserTest
阅读更多内容后,我意识到可能需要添加 require 或包含一个控制器.只有我不明白该怎么做.请告诉我.
after reading more I realized that probably need to add require or include a controller. Only I do not understand how to do it. please tell me.
推荐答案
Rails 中的约定是转换文件中的类名和目录中的模块名.因此,如果您将 UserTest::Test 类放在 app/model 目录中的 test.rb 文件中,则自动加载无法获取您的类.因为搜索 app/model/user_test/test.rb
文件.
The convention in Rails is to convert your Class name in file and your module name in directory. So if you put your UserTest::Test class in test.rb file in your app/model directory, the autoload failed to get your class. Because search on app/model/user_test/test.rb
file.
因此,您可以通过在文件顶部添加 require 来强制"控制器中的 require.如果您将类放在 test.rb 中,则要求是:require 'test.rb'
So you can "force" the require in your Controller by adding a require in top of your file. The require if you put your class in your test.rb is : require 'test.rb'
要知道如何定义您的需求,请考虑您的应用程序的 LOAD_PATH 添加 app/model
目录.所以里面的都可以通过要求目录名和文件名直接添加.
To know how define your require is to think the LOAD_PATH of your application add app/model
directory. So all inside can be add directly by requiring the directory name and file name.
这篇关于Test:Module 的未定义方法“新"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!