3

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

I read this question rails models

added to the model Test in module UserTest

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

and added to the controller

class TestsController < ApplicationController

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

server shows an error: uninitialized constant TestsController::UserTest

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.

Community
  • 1
  • 1
alezhka
  • 738
  • 2
  • 12
  • 29

2 Answers2

12

Never rename a model to the same name of the project. You will get a message like this:

undefined method `new' for Example:Module

The project module priority precedes on the call.

Oswaldo Ferreira
  • 1,339
  • 16
  • 15
7

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.

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'

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.

shingara
  • 46,608
  • 11
  • 99
  • 105
  • Thank you for your reply. question about LOAD_PATH. i added config.autoload_paths += %W(#{config.root}/app/models/) . server shows undefined method `user_test_tests_path'. what is my mistake? – alezhka Mar 09 '12 at 09:38
  • method `user_test_tests_path` are generate by your route. It's not related on require system – shingara Mar 09 '12 at 10:47