Hide user id in url string

In my rails app, I currently have a user loaded, each with a registered user ID.

If I enter my user index and click on the user display page, I get the following sample heading.

localhost: 3000 / users / 3

Now I don’t like it, as it easily allows users to skip users in the header.

How can I do the following so that the user.username field is displayed instead, for example.

local: 3000 / users / adamwest

+6
source share
1 answer

You can define the to_param method in the user model.

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

Then each generated URL will have name instead of id as the user identifier.

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

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

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

I also suggest you take a look at friendly_id gem.

FriendlyId - "Swiss Army bulldozer" traffic jams and permalink plugins for ActiveRecord. This allows you to create beautiful URLs and work with user-friendly strings, as if they were numeric identifiers for the ActiveRecord Model.

+8
source

Source: https://habr.com/ru/post/910269/


All Articles