2

I have a controller: "/app/controllers/analyst/test_orders_controller.rb".

In this file I have:

class Analyst::TestOrdersController < ApplicationController
  def new
    @order = Order.new
  end
end

But I have an error:

uninitialized constant Analyst::TestOrdersController::Order

But I don't want to use Analyst::TestOrdersController::Order.new, I just want to use Order.new. It is strange. What is the problem?

8
  • Is your Order class accessible from rails console? Commented Dec 9, 2014 at 14:51
  • 2
    Try using @order = ::Order.new Commented Dec 9, 2014 at 14:51
  • @Marek_Lipka, Yea, of course. I have about 30 controllers which use this class. Commented Dec 9, 2014 at 14:52
  • @dax, I know this solution, but I think it is just a hack. And what is the matter of this strange behavior? Commented Dec 9, 2014 at 14:53
  • 2
    using ::Order.new actually solves your problem? Commented Dec 9, 2014 at 15:44

2 Answers 2

3

Use ::Order.new The interpreter is looking for the definition of Order under the Analyst module namespace, this happens because the application models are loaded lazily so the file models/order.rb has not been read yet. Adding the general namespace tells it search for the definition in the Rails paths.

The way to confirm this is to add some random function call in the Order model body and see that it's not executed unless you call ::Order explicitly.

Sign up to request clarification or add additional context in comments.

Comments

1

try:

module  Analyst
  class TestOrdersController < ApplicationController
    def new
      @order = Order.new
    end
  end
end

I think it has to do with module nesting: https://cirw.in/blog/constant-lookup

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.