2016-12-15 238 views
2

我正在將我的應用中的/widgets路由重命名爲/thingers,我希望能夠用一行將所有widget相關URL重定向到它們的thinger對應項。重定向通配符匹配

喜歡的東西:

get '/widgets(*anything)', to: redirect('/thinger%{anything}'), 
    as: 'widgets_redirect' 

^^^這並不工作:它通過斜線通過爲%2F30%2F,並沒有通過文件擴展名的。

唯一的工作解決我是在幾行:

get '/widgets', to: redirect('/thingers'), as 'widgets_redirect' 
get '/widgets/:id', to: redirect('/thingers/%{id}') 
get '/widgets/:id/:action.:ext', to: redirect('/thingers/%{id}/%{action}.%{ext}') 
get '/widgets/:id/:action', to: redirect('/thingers/%{id}/%{action}') 

*編輯:交換了最後兩行,否則一個沒有文件擴展名的比賽,並錯誤地處理與延期請求。

如何用單一行覆蓋所有這些情況?

回答

2

The。字符在ActionController :: Routing :: SEPARATORS中定義,其中列出了用於分割URL的特殊字符。這就是爲什麼你所有的分機都被切斷了。

如果你想避免分裂在.S的URL,你需要傳遞一個:限制=> {:yourvalue => /正則表達式/}參數

你可以試試這個與所有的鏈接重定向擴展以及:

這兩條路線會給你你想達到什麼目的:

get '/widget', to: redirect('/thingers') 
get 'widget/:thingy', to: redirect('/thingers/%{thingy}'), :constraints => { :thingy => /.*/ } 
+0

爲什麼不''/.*/包括斜槓也? – tuff

+0

它的確如此。你現在寫的所有鏈接,例如'/ widget/something/another.txt'都會被重定向到'/ thingers/something/another.txt' –

+0

不幸的是它沒有:斜​​線仍然是URL編碼的,而不是通過,所以'/ widgets/info.json'我被重定向到'/ thingers30%2Finfo.json'。我也想知道爲什麼你的解決方案需要兩行,如果斜線可以匹配 - 爲什麼不只是'重定向('/ thingers%{thingy}')'? – tuff