Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide user id in the url bar

In my rails application I currently have a load of users who each have a registered user id.

If I go in to my users index and click on a users show page I get the following example header.

localhost:3000/users/3

Now I don't like this as it easily allows people to skip through users in the header.

How would I go about doing the following so that it shows the user.username field instead e.g.

localhost:3000/users/adamwest

like image 940
user1222136 Avatar asked Mar 08 '12 18:03

user1222136


1 Answers

You can define a to_param method on the User model.

class User
  ...
  def to_param
    name
  end
  ...
end

Then every generated URLs will have name instead of id as a user identifier.

sid = User.new :name => 'sid'
user_path(sid) #=> "/users/sid"

Of course, in the controller, you have to find user by name.

class UsersController
  ...
  def show
    @user = User.find_by_name(params[:id])
  end
  ...
end

I also suggest you to take a look at friendly_id gem.

FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.

like image 67
cutalion Avatar answered Oct 17 '22 08:10

cutalion