路由错误 - 未初始化的常量

Dav*_*vit 32 ruby ruby-on-rails rails-routing

我无法在Rails 3.2.12中解决这个问题,也许我错过了一些东西.

配置/ routes.rb中

get "home/index"
root :to => "home#index"
devise_for :users, :only => :omniauth_callbacks
match 'users/auth/:provider/callback' => 'authentications#create'
match '/auth/:provider/signout' => 'authentications#signout'
Run Code Online (Sandbox Code Playgroud)

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

class AuthenticationsController < ApplicationController
  ...
end
Run Code Online (Sandbox Code Playgroud)

应用程序/模型/ authentication.rb

class Authentication < ActiveRecord::Base
  ...
end
Run Code Online (Sandbox Code Playgroud)

我认为它应该符合我目前的知识,但有些东西我想念.

我的问题是告诉我有什么问题.

计数错误

uninitialized constant AuthenticationsController

这是一条显示在的消息 http://localhost:3000/auth/facebook/signout

alf*_*alf 50

Rails要求文件名与类名匹配.因此,您应该重命名app/controllers/authentication_controller.rbapp/controllers/authentications_controller.rb.

  • 哦.谢谢你@alfonso.我以这种方式创建了控制器`rails g controller authentication`,因此文件本身被命名为`authentication_controller.rb`,也许我更改了类名.非常感谢您回答这样一个众所周知的问题. (2认同)
  • @Davit提示:在生成控制器时应始终使用复数. (2认同)

Jar*_*ard 5

虽然这个问题已得到解答,但我发现了另一个案例,我收到了这个错误,并希望在此处记录后代.

如果您的routes.rb文件中定义了两个类似的路由而没有相应的控制器,您将获得未初始化的常量错误.

重现步骤:

rails generate scaffold foobar name:string
bundle exec rake db:migrate
Run Code Online (Sandbox Code Playgroud)

添加资源:foobars到routes.rb到一个新的范围(注意:foobars资源已经在scaffold生成期间自动添加到routes.rb的顶部),如下所示:

  resources :foobars

  ########################################
  # SUPER
  ########################################

  constraints host: ENV['SUPER_HOST'] do
    scope module: :super do
      resources :foobars
      get '/' => 'super#index'

    end
  end
Run Code Online (Sandbox Code Playgroud)

现在,将/ app/views/foobars移动/ app/views/super/foobars ,并将/app/controllers/foobars_controller.rb移动到/app/controllers/super/foobars_controller.rb 确保foobars_controller.rb在Super模块中:

class Super::FoobarsController < ApplicationController
Run Code Online (Sandbox Code Playgroud)

现在转到your.dev.server/foobars /你应该得到这个错误:路由错误未初始化的常量FoobarsController

现在,删除资源:路由开头的foobars.rb现在应该可以工作了!

我花了一段时间才弄清楚为什么我收到这个错误,我没有意识到生成脚手架会在routes.rb中添加一个条目