Reputation: 31
I want the users#show
action to be available under the attribute username instead of the user_id.
So if I go to a user, I want the url to show something like users/some_username
instead of users/22
My Routes:
resources :users, only: %i(show edit update) do
member do
get :follows
get :statistic
get :my_topics, path: :topics
end
end
Upvotes: 0
Views: 58
Reputation: 10413
Just to extend on nice the answer from Robert: Another way would be to use a gem that is dedicated to do exactly this. One of the many options could be https://github.com/norman/friendly_id.
The gist of it is that you add a field to your user model (here, slug
, that holds the url segment) which you generate in your model. For fetching records, a method is used that takes either the id as before, or the slug.
In your case, this might be an overkill unless you consider to have the same url requirement for other routes and models.
Side note: I have no affiliation with this project, I just used it a few times before.
Upvotes: 1
Reputation: 827
You can add a param
option to the routes.
resources :users, param: :name, only: %i(show edit update) do
member do
get :follows
get :statistic
get :my_topics, path: :topics
end
end
Using rake routes | grep user
will result in the following.
follows_user GET /users/:name/follows(.:format) users#follows
statistic_user GET /users/:name/statistic(.:format) users#statistics
my_topics_user GET /users/:name/topics(.:format) users#my_topics
edit_user GET /users/:name/edit(.:format) users#edit
user GET /users/:name(.:format) users#show
PATCH /users/:name(.:format) users#update
PUT /users/:name(.:format) users#update
Upvotes: 1