Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails custom route with constraints - regexp anchor characters are not allowed in routing requirements

I have the following route:

  get 'users/:user_id/:name', to: 'profiles#show',
    :constraints => { :name => /[a-zA-Z0-9_]+$/ }, as: 'user_profile'

Which produces the error:

Regexp anchor characters are not allowed in routing requirements: /[a-zA-Z0-9_]+$/

So I get that the ^ character isn't allowed, but not sure what character is producing this particular routing error.

like image 237
keruilin Avatar asked Nov 04 '12 20:11

keruilin


People also ask

What is match in Rails routes?

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

What are RESTful routes in Rails?

In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.

What is namespace in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.


1 Answers

The regex anchors are ^ and $, but they don't achieve anything here. "(Y)ou don’t need to use anchors because all routes are anchored at the start.".

So the constraint:

:constraints => { :name => /[a-zA-Z0-9_]+/ }

will do what you want - ensure the name is composed of 1 or more of those characters, and nothing else. BTW you can simplify the regex:

:constraints => { :name => /\w+/ }
like image 51
mahemoff Avatar answered Sep 22 '22 20:09

mahemoff