Hide user id in the url bar

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

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

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!