skip to Main Content

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


  1. For things to work exactly like you would want, do this instead –

    resources :users
    get '/users/:id/granted', to: 'users#show', as: :granted
    
    Login or Signup to reply.
  2. 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) — use member and collection routes.

    So, to add /granted member route inside the users resource, you can write:

    resources :users do
      get 'granted', on: :member
    end
    

    Moreover, to point the newly added route to an existing controller action (users#show, in your case), just pass it over :to option:

    resources :users do
      get 'granted', to: 'users#show', on: :member
    end
    

    If you have other existing member routes under the users resource, then add the route inside the member block instead:

    resources :users do
      member do
        # other custom member routes
        get 'granted', to: 'users#show'
      end
    end
    

    rake routes output for your specific granted route:

    granted_user GET    /users/:id/granted(.:format) users#show
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search