将设计路由从 ID 更改为用户名 [英] Change devise route from ID to Username
问题描述
我尝试使用帖子更改路由以指向用户名.我知道这很简单,但出于某种原因,我目前无法计算它.我也尝试了设计文档页面上的所有内容.
我只想让路由布局使用用户名而不是 id 并且没有用户前缀.喜欢:
代替
class User
在你的控制器中制作
@user = User.find_by_username(params[:id])
代替
@user = User.find(params[:id])
这将使您的路由类似于 http://example.com/users/username>
要制作您想要的东西,您可以执行以下路线:
resources :users, :path =>'' 做# 嵌套资源...结尾
因此,user_path(@user) 将使 url http://example.com/username但这不是一个好习惯,因为它不是 REST.我建议你留下像 http://example.com/users/username
这样的网址I have tried using the post to change the routes to point at the username. I know this is simple, but for some reason I can't compute it at the moment. I have tried everything on the devise documentation page as well.
I just want to have the routes layout to use the username instead of id and not have the users prefix. Like:
instead of
class User < ActiveRecord::Base
def to_param
username
end
end
in your controller make
@user = User.find_by_username(params[:id])
instead of
@user = User.find(params[:id])
this will make your routes like http://example.com/users/username
to make what you want, you can do route like:
resources :users, :path => '' do
# nested resources...
end
so, user_path(@user) will make url http://example.com/username but It's not a good practice, cause it's not a REST. I advise you to leave urls like http://example.com/users/username
这篇关于将设计路由从 ID 更改为用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!