Home > Mobile >  How to give custom names to nested routes in rails
How to give custom names to nested routes in rails

Time:03-24

I have a RoR application where I want to apply custom routes names, right now I have this:

localhost:3000/users/:id/groups/:id

And I want something like

localhost:3000/users/username/groups/groupname

So far,I've been able to create the route for the user and I ended up with:

localhost:3000/users/username

I did that by adding to_param into my user model, but once I click to go into my groups,it goes back to the :id instead of the username. I also tried to apply the to_param into my group model as well, but it did nothing.

These are my routes:

Rails.application.routes.draw do
  devise_for :users
  devise_scope :user do get '/users/sign_out' => 'devise/sessions#destroy' end
  resources :users, only: [:index, :show] do
    resources :groups, only: [:index, :show, :new, :create]
    resources :entities, only: [:index, :show, :new, :create]
  end

  root "users#index"
end

So I don't know how to achieve that, is the problem in the routes file? or is it within the models?

CodePudding user response:

From rails 5 you can use :param to specify a different identifier

resources :users, param: :username do 
  resources :groups, param: :groupname
end

I believe this will give you users/<username>/groups/<groupname>.

  • Related