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

23,860

Solution 1

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

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

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/

Share:
23,860

Related videos on Youtube

iGEL
Author by

iGEL

Updated on July 05, 2022

Comments

  • iGEL
    iGEL almost 2 years

    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?

  • iGEL
    iGEL over 13 years
    Thanks. The regexp you quoted has a typo thought, it should be /[^\/]+/, not /[^\/]/+. But thats an error in the original guide.
  • DavidJ
    DavidJ about 12 years
    The syntax would be, for example: get "/:user/contributions" => 'users#contributions', :constraints => {:id => /[^\/]+/}
  • Kris
    Kris over 5 years
    /.*/ also works, I don't know regex well enough to tell the difference.
  • Zabba
    Zabba about 5 years
    got more details @RyanGlen ? it does work on the indicated ruby on rails versio.
  • prashant
    prashant almost 5 years
    In Rails 6 I had to set format: false, defaults: {format: 'html'} to get Rails to stop trying to treat the dot segment as a file extension indicating a content type.