Ruby on Rails Exception:Routing Error

当开始做Ruby on Rails实际编程时,对于初学者而言总会有些让人感到未知的Exception, 上次以手工方式写了一个简单的Rails Application, 今天下午换用Red Rails工具编译器,和上次关于Rails配置完全相同 却出现一个Exception: Routing Error. 具体截图如下:

提示Exception 信息:"No Route matches:/say/hello with {:method=>get}" . 

<1>Rails下两个目录Public/Config

<1.1>Public目录

Rails框架是基于MVC架构的,在创建的项目Public目录中是我们要暴露给用户文件,其中包含关键文件分发器-dispatcher. 其中包含三个文件:dispatch.cgi/dispatch.fcgi/dispatch.rb.而分发器主要作用是: 负责接收用户从浏览器发送的请求,并将这些请求引导指定程序的程序代码, 也就是传送给MVC中Controller. 可以看出它是起引导请求的作用.

<1.2>Config目录

Config目录顾名思义,是对整个Rails Application进行配置, 其中涉及数据库/运行环境,另外一个就是路由规则定义, 这个指定文件为routes.rb

而一般对于Routing Error这类异常应该首先查看Rails Application路由访问规则. 打开文件:

ActionController::Routing::Routes.draw do |map|
  # The priority is based upon order of creation: first created -> highest priority.

  # Sample resource route (maps HTTP verbs to controller actions automatically):
  #   map.resources :products
  
  # You can have the root of your site routed with map.root -- just remember to delete public/index.html.
  # map.root :controller => "welcome"

  # See how all your routes lay out with "rake routes"

  # Install the default routes as the lowest priority.
  # Note: These default routes make all actions in every controller accessible via GET requests. You should
  # consider removing or commenting them out if you're using named routes and resources.
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

 能够看到Rails Application默认的路由规则访问定义:主要有两种访问方式 id则是From附属参数.如果我们定义好了Controller, 按照Rails访问路径:http://localhost:3000/say/hello 这种方式违背了Rails 路由规则,导致我们请求找不到指定Controller来处理. 只要稍作修改在原有路径基础上随意添加一个参数:

http://localhost:3000/say/hello/12 在来尝试访问:

Template Is Missing提示是因为我们没有指定位置创建View或是我们创建的View页面放错位置导致无法访问, 按照提示在Rails Application 创建的APP/Views/Say/下创建一个Erb文件.再次访问:

you see!这样我就访问View具体内容.

<2>路由规则问题

如上打开系统默认存放的路由规则文件routes.rb. 有人会疑问可以自定义路由访问规则?Rails中是允许的, 但是我在尝试中遇到一个问题,就是新建立的Route路由规则不起作用,后来看了相关文档发现: 对于新建的路由规则,需要重新其中Rails Server才能生效.

另外关于路由关联最多就是Rails版本问题了. 有初学者在使用Rails 3时常常遇到这样问题. 这是因为Rails 3默认定义路由规则和以前版本发生一定变化. 所以在Ruby社区中很多人建议使用稳定Rails 2.3.8版本.

<3>Rails环境

最后说明一下我测试的Rails环境参数:

原文地址:https://www.cnblogs.com/chenkai/p/1787157.html