天天看點

Ruby on Rails Exception:Routing Error

當開始做Ruby on Rails實際程式設計時,對于初學者而言總會有些讓人感到未知的Exception, 上次以手工方式寫了一個簡單的Rails Application, 今天下午換用Red Rails工具編譯器,和上次關于Rails配置完全相同 卻出現一個Exception: Routing Error. 具體截圖如下:

<a href="http://blog.51cto.com/attachment/201201/145410634.png" target="_blank"></a>

提示Exception 資訊:"No Route matches:/say/hello with {:method=&gt;get}" . 

&lt;1&gt;Rails下兩個目錄Public/Config

&lt;1.1&gt;Public目錄

Rails架構是基于MVC架構的,在建立的項目Public目錄中是我們要暴露給使用者檔案,其中包含關鍵檔案分發器-dispatcher. 其中包含三個檔案:dispatch.cgi/dispatch.fcgi/dispatch.rb.而分發器主要作用是: 負責接收使用者從浏覽器發送的請求,并将這些請求引導指定程式的程式代碼, 也就是傳送給MVC中Controller. 可以看出它是起引導請求的作用.

&lt;1.2&gt;Config目錄

Config目錄顧名思義,是對整個Rails Application進行配置, 其中涉及資料庫/運作環境,另外一個就是路由規則定義, 這個指定檔案為routes.rb

<a href="http://blog.51cto.com/attachment/201201/145417176.png" target="_blank"></a>

而一般對于Routing Error這類異常應該首先檢視Rails Application路由通路規則. 打開檔案:

ActionController::Routing::Routes.draw do |map|   

  # The priority is based upon order of creation: first created -&gt; 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 =&gt; "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 在來嘗試通路:

<a href="http://blog.51cto.com/attachment/201201/145422270.png" target="_blank"></a>

Template Is Missing提示是因為我們沒有指定位置建立View或是我們建立的View頁面放錯位置導緻無法通路, 按照提示在Rails Application 建立的APP/Views/Say/下建立一個Erb檔案.再次通路:

<a href="http://blog.51cto.com/attachment/201201/145428619.png" target="_blank"></a>

you see!這樣我就通路View具體内容.

&lt;2&gt;路由規則問題

如上打開系統預設存放的路由規則檔案routes.rb. 有人會疑問可以自定義路由通路規則?Rails中是允許的, 但是我在嘗試中遇到一個問題,就是建立立的Route路由規則不起作用,後來看了相關文檔發現: 對于建立的路由規則,需要重新其中Rails Server才能生效.

另外關于路由關聯最多就是Rails版本問題了. 有初學者在使用Rails 3時常常遇到這樣問題. 這是因為Rails 3預設定義路由規則和以前版本發生一定變化. 是以在Ruby社群中很多人建議使用穩定Rails 2.3.8版本.

&lt;3&gt;Rails環境

最後說明一下我測試的Rails環境參數:

<a href="http://blog.51cto.com/attachment/201201/145435479.png" target="_blank"></a>

本文轉自chenkaiunion 51CTO部落格,原文連結:http://blog.51cto.com/chenkai/764765