在 url 栏中隐藏用户 ID [英] Hide user id in the url bar

查看:15
本文介绍了在 url 栏中隐藏用户 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Rails 应用程序中,我目前有大量用户,每个用户都有一个注册用户 ID.

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

localhost:3000/users/3

现在我不喜欢这样,因为它很容易让人们跳过标题中的用户.

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

我将如何进行以下操作,以便显示 user.username 字段,例如

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

localhost:3000/users/adamwest

localhost:3000/users/adamwest

推荐答案

您可以在 User 模型上定义一个 to_param 方法.

You can define a to_param method on the User model.

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

那么每个生成的 URL 都会有 name 而不是 id 作为用户标识符.

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

我还建议您查看 friendly_id gem.

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

FriendlyId 是重击和永久链接的瑞士陆军推土机"ActiveRecord 的插件.它允许您创建漂亮的 URL 和使用人性化的字符串,就好像它们是数字 idActiveRecord 模型.

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.

这篇关于在 url 栏中隐藏用户 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆