2014-01-28 25 views
0

redirect_to的有效的URL如何救助,如果用戶訪問了錯誤的URL,然後應用程序中使用過濾器之前重定向自動對有效的URL,例如我有合法的URL是這樣的:如果用戶訪問的網址有誤救援與軌道

http:://localhost:3000/stores/ 

,如果我有錯網址的瀏覽器,例如像這樣訪問:

http://localhost:3000/test/ 

我希望我的Rails應用程序自動重定向到有效的URL =>http:://localhost:3000/stores/,如果我嘗試訪問錯誤的URL像上面。那是怎麼回事?

+0

是「重定向」路線動態還是靜態? –

回答

0

由於經驗法則是,以顯示404給用戶,當他們進入錯誤的地址。如果你真的需要將用戶從不確定的URL重定向,並且您確信這就是你的使用情況,您可以使用路由轉接呼叫這樣做:

方法如下:http://guides.rubyonrails.org/routing.html#redirection

,併爲您的通配符重定向它可能與此類似:

get '*path' => redirect('/') 在routes.rb中

結束時再次 - 我建議不這樣做的。

+0

我添加'* a',以:在我的路線中重定向('/ stores'),但是當我嘗試訪問url => http:// localhost:3000/a時。我仍然得到錯誤 – tardjo

+0

對不起,更正了我的答案 - 它的'''get'* path'=> redirect('/')''' – madsheep

+0

http://stackoverflow.com/questions/4132039/rails-redirect-all- unknown-routes-to-root-url – madsheep

0

我喜歡那些三個清潔rescue_from條款,一個(或全部)應該做的伎倆:

在你application_controller.rb

rescue_from ActionController::RoutingError,  :with => :redirect_missing 
    rescue_from ActionController::UnknownController, :with => :redirect_missing 
    rescue_from ActionController::UnknownAction,  :with => :redirect_missing 

    def redirect_missing 
    # do your thing, e.g. 
    redirect_to root_path 
    end 

希望幫助

+0

這樣做是一個壞主意 - 拯救錯誤不應該是你的控制流。路線在那裏處理路徑;) – madsheep