Jim ruther Nill wrote in post #1019405:
On Wed, Aug 31, 2011 at 10:51 PM, 7stud â [email protected] wrote:
match â/:idâ => âusers/showâ
having this line will match any controllerâs index action
Ah, I see. :id will match anything, e.g.
/dog
/frog
/users
/pages
/hello_world
/1
/200
in the Segments Constraints section of the rails guide, youâll see the
first
line of code.
following that code, you can use
match âusers/:idâ => âusers#showâ, :constraints => { :id => /\d/ }, :
âŚand the constraint there says to only match a number in the :id
position of the url. But is that route any different than the show
route created by resources()? It was my understanding that the op
wanted a url consisting of only a number, so I think the route should be
more like:
match â/:idâ => users#show, :constraints => {:id => /\d+/}, :via =>
âgetâ
via => :get
the via option is important so that it will only match get requests.
I wonder why people post ambiguous questions and expect people who read
them to know what they are thinkingâinstead of giving a simple example
that leaves nothing in doubt.
However, that will still match routes like:
/a2b
It looks like you can write a custom constraint pretty easily, though:
class UserShowConstraint
def matches?(request)
request.path =~ /
\A #start of string
\/ #forward slash
\d+ #one or more digits
\z #end of string
/x
end
end
And then use the route:
match â*idâ => âuser#showâ, :constraints => UserShowConstraint.new,
:via => âgetâ
That will match only urls of the form:
/1
/123
and wonât match urls of the form:
/2ab
/a2b
/2b