81

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?

slhck
  • 36,575
  • 28
  • 148
  • 201
iGEL
  • 16,540
  • 11
  • 60
  • 74

3 Answers3

149

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 => /[^\/]+/ }
Leopd
  • 41,333
  • 31
  • 129
  • 167
Zabba
  • 64,285
  • 47
  • 179
  • 207
  • 4
    Thanks. The regexp you quoted has a typo thought, it should be /[^\/]+/, not /[^\/]/+. But thats an error in the original guide. – iGEL Mar 20 '11 at 17:14
  • The syntax would be, for example: get "/:user/contributions" => 'users#contributions', :constraints => {:id => /[^\/]+/} – DavidJ Apr 11 '12 at 16:53
  • `/.*/` also works, I don't know regex well enough to tell the difference. – Kris Oct 05 '18 at 15:47
  • got more details @RyanGlen ? it does work on the indicated ruby on rails versio. – Zabba Jun 26 '19 at 19:47
  • 2
    In Rails 6 I [had to set](https://stackoverflow.com/a/57895695/27358) `format: false, defaults: {format: 'html'}` to get Rails to stop trying to treat the dot segment as a file extension indicating a content type. – David Moles Sep 11 '19 at 19:39
9

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|$|\/)/
Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
7

Looks like the following link answers your question.

http://avdi.org/devblog/2010/06/18/rails-3-resource-routes-with-dots-or-how-to-make-a-ruby-developer-go-a-little-bit-insane/

huntsfromshadow
  • 1,085
  • 8
  • 12