Undefined method `new 'for test: module

Hello I have a namespace conflict issue. I have a model: Test and controller TestsController. server displays error

undefined method `new' for Test:Module

      

I read this question rail models

added to Test model in UserTest module

module UserTest
  class Test < ActiveRecord::Base
  ....
  end
end

      

and added to controller

class TestsController < ApplicationController

  def new
    @test = UserTest::Test.new
    @test.questions.build
    @title = "New test"
  end
 ...
end

      

server shows error: uninitialized constant TestsController::UserTest

after reading more i realized that i probably need to add request or enable controller. Only I don't understand how to do it. please tell me.

+3


source to share


2 answers


The convention in Rails is to convert your class name to a file and your module name to a directory. Therefore, if you put your UserTest :: Test class in the test.rb file in your application / model directory, autoloading will fail to retrieve your class. Because searching in the file app/model/user_test/test.rb

.

So, you can "force" the demand in your controller by adding the demand to the beginning of your file. Requirement if you put your class in your test.rb:require 'test.rb'



To see how to determine your requirement, consider that your application's LOAD_PATH adds a directory app/model

. So everything inside can be added directly, requiring a directory name and a file name.

+3


source


Never rename a model to the same project name. The following message appears:

undefined method `new' for Example:Module

      



The priority of the project unit precedes the call.

+8


source







All Articles