Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change devise route from ID to Username

I have tried using the post to change the routes to point at the username. I know this is simple, but for some reason I can't compute it at the moment. I have tried everything on the devise documentation page as well.

Drawing username routes

I just want to have the routes layout to use the username instead of id and not have the users prefix. Like:

http://example.com/username

instead of

http://example.com/users/1

like image 655
Matthew Harrison Avatar asked Apr 17 '11 20:04

Matthew Harrison


1 Answers

class User < ActiveRecord::Base
  def to_param
    username
  end
end

in your controller make

@user = User.find_by_username(params[:id])

instead of

@user = User.find(params[:id])

this will make your routes like http://example.com/users/username

to make what you want, you can do route like:

resources :users, :path => '' do
  # nested resources...
end

so, user_path(@user) will make url http://example.com/username but It's not a good practice, cause it's not a REST. I advise you to leave urls like http://example.com/users/username

like image 125
sandrew Avatar answered Oct 23 '22 01:10

sandrew