使用通配符匹配重定向

时间:2016-12-15 20:50:23

标签: ruby-on-rails redirect routing

我正在将我的应用中的/widgets路由重命名为/thingers,并且我希望能够将所有widget相关的网址重定向到其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}')

* edit:交换最后两行,否则没有文件扩展名的行匹配并错误地处理带扩展名的请求。

如何用一行覆盖所有这些案例?

1 个答案:

答案 0 :(得分:2)

。 character在ActionController :: Routing :: SEPARATORS中定义,它列出了用于拆分URL的特殊字符。这就是为什么所有扩展都会被切断的原因。

如果您想避免在.s处拆分网址,则需要传递:constraints => {:yourvalue => / regexp /}参数

您也可以尝试使用扩展程序重定向所有链接:

这两条路线将为您提供您想要实现的目标:

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