Reputation: 34884
I have a constraint:
get "test/:test_val" => "home#test", constraints: { test_val: /\d{4}/ }
I need it to accept only 4 digits. However, it doesn't seem to work because there's no error being thrown due to this constraint. What's up with it?
Upvotes: 0
Views: 146
Reputation: 16002
Your route is absolutely correct and should work as it's working for me(I get these errors when I change my number of digits in route)-
routes I defined in my app:
get 'users/:id', to: 'users#show', constraints: { id: /\d{4}/ }
Error I get:
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User with id=1234
Which means it is working while won't recognize the route if digits are more or less than 4:
Routing Error
No route matches [GET] "/users/123456"
So, are you sure that you don't have any other route defined with /test/:test_val
above this route which is overriding this one?
Also note that as @Amadan mentioned in his answer to use regexp anchors. Which will not work. You can find this documented in Rails routing from outside in guide section: 3.8 Segment Constraints. It clearly says:
:constraints takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work:
get '/:id', to: 'posts#show', constraints: {id: /^\d/}
However, note that you don't need to use anchors because all routes are anchored at the start.
I hope that helps.
Upvotes: 1
Reputation: 198314
/\d{4}/
will test if there are four consecutive digits anywhere in the string. Thus, 123456789
matches, because 1234
satisfies the test. You probably want to anchor the start and the end of the regular expression:
/^\d{4}$/
Upvotes: 0