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

Ruby on-RailsRuby on-Rails-3Routing

Ruby on-Rails Problem Overview


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.

My route:

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

Any ideas?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

That would for example be:

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

Solution 2 - Ruby on-Rails

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|$|\/)/

Solution 3 - Ruby on-Rails

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniGELView Question on Stackoverflow
Solution 1 - Ruby on-RailsZabbaView Answer on Stackoverflow
Solution 2 - Ruby on-RailsChristopher OezbekView Answer on Stackoverflow
Solution 3 - Ruby on-RailshuntsfromshadowView Answer on Stackoverflow