得到"未初始化的常量ApplicationController"在rails应用程序中

时间:2015-10-31 07:53:51

标签: ruby-on-rails ruby ruby-on-rails-4

我正在尝试学习Rails 4框架并遵循官方doc

我运行了以下命令:

rails new fold

它创建了一个新项目

rails generate controller home index

生成home_controllerviews/home/index.html.erb

home_controller的内容:

class HomeController < ApplicationController
 def index
 end
end

对于路由,我在routes.rb

中添加了以下代码
 get 'home/index' => 'home#index'

运行我正在运行的应用程序后:

uninitialized constant ApplicationController

我在这里做错了什么?这是Stacktrace

app/controllers/home_controller.rb:1:in `<top (required)>'
activesupport (4.2.4) lib/active_support/inflector/methods.rb:261:in `const_get'
activesupport (4.2.4) lib/active_support/inflector/methods.rb:261:in `block in constantize'
activesupport (4.2.4) lib/active_support/inflector/methods.rb:259:in `each'
activesupport (4.2.4) lib/active_support/inflector/methods.rb:259:in `inject'
activesupport (4.2.4) lib/active_support/inflector/methods.rb:259:in `constantize'
actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:72:in `controller_reference'
actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:62:in `controller'
actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:41:in `serve'
actionpack (4.2.4) lib/action_dispatch/journey/router.rb:43:in `block in serve'
actionpack (4.2.4) lib/action_dispatch/journey/router.rb:30:in `each'
actionpack (4.2.4) lib/action_dispatch/journey/router.rb:30:in `serve'
actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:821:in `call'

代码有什么问题?

4 个答案:

答案 0 :(得分:2)

您是否有 application.rb 文件?此文件应位于 app / controllers 内。所有其他控制器都继承自此控制器。最小的设置看起来像这样:

class ApplicationController < ActionController::Base
end

答案 1 :(得分:0)

这样做:

#app/controllers/home_controller.rb
class HomeController < ActionController::Base
  def index
  end
end

这应该暂时解决。

-

要永久修复它,您应该将以下文件添加到您的应用中:

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
   def index
   end
end

您还应该将home_controller更改回以下内容:

#app/controllers/home_controller.rb
class HomeController < ApplicationController
...

答案 2 :(得分:0)

您的应用程序控制器应包含此

应用程序/控制器/ application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

end

答案 3 :(得分:0)

  

未初始化的常量ApplicationController

application_controller.rb中应该app/controllers因为。{ ApplicationController实际上是应用程序中 每个其他控制器 将要继承的类(尽管这不是强制性的)。

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
end