【问题标题】:Sometimes getting an "Invalid Route Name" Error in Rails有时在 Rails 中出现“无效的路由名称”错误
【发布时间】:2015-05-17 02:11:14
【问题描述】:

当我尝试在 localhost 中加载我的 Rails 应用程序时,我偶尔会收到以下错误。

无效的路由名称,已在使用中:'root' 您可能使用 :as 选项定义了两个同名的路由,或者您可能覆盖了已由同名资源定义的路由。对于后者,您可以限制使用 resources 创建的路由,如下所述:http://guides.rubyonrails.org/routing.html#restricting-the-routes-created

由于某种原因,它只会时不时发生,并且通常会在我刷新一次页面后消失。它所调用的文件有这个作为代码(导致指示错误的行):

Rails.application.routes.draw do
  get 'welcome/index'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".

# You can have the root of your site routed with "root"

  Rails.application.routes do
    resources :articles
    root 'welcome#index' #-->This is the line that causes the error
  end

  resources :articles do
    resources :comments
  end
end

我真的是 Rails 的新手,我不确定是什么导致了问题,或者如果我真的在网络上托管这个初学者项目是否会成为问题。另外,如果有帮助,我正在运行 Ruby 2.2.2 和 Rails 4.2.1。

提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您将 (Rails.application.routes) 嵌套在 (Rails.application.routes.draw) 中。运行 rake routes,你会看到你有两次文章的资源。此外,您有 root 'welcome#index' 嵌套在里面,这就是您收到错误的原因。你的路线应该是这样的

    Rails.application.routes.draw do
      get 'welcome/index' => 'welcome#index'
      root 'welcome#index' 
      resources :articles do
        resources :comments
      end
    end
    

    请注意,您的应用程序含义(/)和(/welcome/index)的路由都指向欢迎控制器索引操作。您实际上并不需要 get 'welcome/index' => 'welcome#index',您可以删除该行并在需要欢迎控制器的索引操作时使用 root。

    【讨论】:

    • 啊,完美,就是这样!非常感谢!
    【解决方案2】:

    尝试使用“完整”语法。

    root :to=> "some#action"
    

    【讨论】:

      【解决方案3】:

      你有两条路由指向同一个页面index,去掉你的get路由

      get 'welcome/index'
      

      您的根路由也是嵌套的,应该移到外面,因为根路由是整个应用程序的根,而不是特定资源

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-18
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多