I’m new to rails routes…
I’m trying to create an alias route for my
resources :users
^ /users/123
My goal is to add a /granted
at the end of the URL so something like /users/123/granted
I’m trying to add a get
to create another route for the same controller action… I need this for the SEO
get '/users/:id/granted', to: 'users#show', as: :granted
^ I’m expecting this to generate /users/:id/granted
but I keep getting…
/users/:user_id/users/:id/granted
Looks like it’s attaching a different format, with :user_id
as the parameter… but I need the parameter to stay as :id
I tried
get '/granted', to: 'users#show', as: :granted
it generates /users/:user_id/granted
which is not okay because as I mentioned above… I want the parameter key to stay as :id
2
Answers
For things to work exactly like you would want, do this instead –
I can see that you need to sort things out for 2 tasks: defining a new route (
/users/:id/granted
) and making the route an alias for an existing controller action (users#show
).Before that, let me help you getting familiar with one of the Rails best practices when you need to add more custom actions to a RESTful resource (other than the 7 default actions created by
resources :users
) — usemember
andcollection
routes.So, to add
/granted
member route inside theusers
resource, you can write:Moreover, to point the newly added route to an existing controller action (
users#show
, in your case), just pass it over:to
option:If you have other existing member routes under the
users
resource, then add the route inside themember
block instead:rake routes
output for your specificgranted
route: