Ruby-on-rails 为什么参数中带点的路由匹配失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5369654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:43:02  来源:igfitidea点击:

Why do routes with a dot in a parameter fail to match?

ruby-on-railsruby-on-rails-3routing

提问by iGEL

I've got an route for my users like /iGEL/contributions, which works fine. But now a user registered with a name like 'A.and.B.', and now the route fails to match, since the name contains dots.

我为我的用户提供了一条路线,例如/iGEL/contributions,效果很好。但是现在一个用户注册了一个像“A.and.B.”这样的名字,现在路由无法匹配,因为名字包含点。

My route:

我的路线:

get "/:user/contributions" => 'users#contributions'

Any ideas?

有任何想法吗?

回答by Zabba

See the blue info box here:

请参阅此处的蓝色信息框:

By default dynamic segments don't accept dots – this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this – for example :id => /[^\/]+/allows anything except a slash.

默认情况下,动态段不接受点——这是因为点被用作格式化路由的分隔符。如果您需要在动态段中使用一个点,请添加一个覆盖它的约束——例如,:id => /[^\/]+/允许除斜杠之外的任何内容。

That would for example be:

例如,这将是:

get "/:user/contributions" => 'users#contributions', :constraints => { :user => /[^\/]+/ }

回答by Christopher Oezbek

If your variable segment is the last one, then using the [^\/]regex will also eat the format. In such a case rather use:

如果您的变量段是最后一个,那么使用[^\/]正则表达式也会占用格式。在这种情况下,而是使用:

/([^\/]+?)(?=\.json|\.html|$|\/)/