For Ruby on Rails 4.1.4 (and possibly earlier versions) you need to do what both j.. and Ujjwal suggested:
1) In config/routes.rb
, add:
resources :user, param: :username
2) In app/models/user.rb
, add:
def to_param
username
end
In you only do #1 then all your routes will be correct, as can be seen from rake routes
:
$ rake routes
Prefix Verb URI Pattern Controller#Action
user_index GET /user(.:format) user#index
POST /user(.:format) user#create
new_user GET /user/new(.:format) user#new
edit_user GET /user/:username/edit(.:format) user#edit
user GET /user/:username(.:format) user#show
PATCH /user/:username(.:format) user#update
PUT /user/:username(.:format) user#update
DELETE /user/:username(.:format) user#destroy
However the helper methods that construct a url based on a User
instance will still include the id
in the url, e.g. /user/1
. To get the username
in the constructed urls, you need to override to_param
as in #2.