隐藏网址栏中的用户ID [英] Hide user id in the url bar
问题描述
在我的Rails应用程序中,我目前有一批用户,每个用户都有一个注册用户ID。
如果我进入我的用户索引并单击用户显示页面我得到以下示例头文件。
localhost:3000 / users / 3
因为它很容易让人跳过标题中的用户。
我会如何去做以下事情,以便它显示user.username字段,例如
localhost:3000 / users / adamwest
用户模型上的 to_param
方法。
class User
...
def to_param
名称
结束
...
结束
然后,每个生成的URL都将具有名称
而不是 id
作为用户标识符。
sid = User.new:name => 'sid'
user_path(sid)#=> / users / sid
当然,在控制器中,您必须按名称查找用户。
class UsersController
...
def show
@user = User.find_by_name( params [:id])
end
...
end
我也建议你看看 friendly_id 宝石。
FriendlyId是ActiveRecord的slugging和permalink
插件的Swiss Army推土机。它允许你创建漂亮的URL,
使用人性化的字符串工作,就像它们是
ActiveRecord模型的数字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
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
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.
这篇关于隐藏网址栏中的用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!