【问题标题】:Why route root did not work?为什么路由根不起作用?
【发布时间】:2015-05-29 12:58:50
【问题描述】:

我正在学习 Michael Hartl 的教程 Ruby on Rails 教程,并尝试完成第 3.4.4 节中的最后一步。当我将 routes.rb 更改为

Rails.application.routes.draw do
 root 'static_pages#home'
 get  'static_pages/help'
 get  'static_pages/about'
end

然后重新启动http://localhost:3000/static_pages,他们说“我们很抱歉,但出了点问题”。然后我重新启动http://localhost:3000/static_pages/help,它就可以工作了。然后我通过

检查路线
rake routes

结果显示:

Prefix Verb URI Pattern                   Controller#Action
          root GET  /                             static_pages#home
static_pages_help GET  /static_pages/help(.:format)  static_pages#help
static_pages_about GET  /static_pages/about(.:format) static_pages#about

我检查了文件 static_pages_controller.rb 中的内容,与教程中的内容没有区别。谁能告诉我怎么了?

【问题讨论】:

  • 你不是倒退了吗?您的路由定义是否意味着如果您访问http://localhost:3000/,它将调用控制器static_pages 上的操作home?您要映射什么 URL(以及映射到什么控制器/操作)?
  • 解决了这个问题。请原谅我是网络开发的新手。

标签: ruby-on-rails


【解决方案1】:

好吧,有了这个路由映射root 'static_pages#home',你说,当你点击http://localhost:3000/ url时,你将被映射到StaticPages控制器的home动作。

但是您没有为http://localhost:3000/static_pages 定义任何映射,根据route.rb 文件,它的url 不正确。这就是你得到错误的原因。

阅读rake routes输出的第一行,它清楚地说明了你定义了什么。

【讨论】:

    【解决方案2】:

    root 'static_pages#home' 行等同于get '/', to: 'static_pages#home'。这意味着 URL localhost:3000/ 被路由到 StaticPages 控制器上的 #home 操作。

    如果您希望localhost:3000/static_pages 指向#home 操作,请添加以下行:

    get 'static_pages', to: 'static_pages#home'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-31
      • 2011-12-07
      • 1970-01-01
      • 2021-11-02
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多