将设计路由从 ID 更改为用户名 [英] Change devise route from ID to Username

查看:11
本文介绍了将设计路由从 ID 更改为用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用帖子更改路由以指向用户名.我知道这很简单,但出于某种原因,我目前无法计算它.我也尝试了设计文档页面上的所有内容.

绘制用户名路径

我只想让路由布局使用用户名而不是 id 并且没有用户前缀.喜欢:

http://example.com/username

代替

http://example.com/users/1

解决方案

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.

Drawing username routes

I just want to have the routes layout to use the username instead of id and not have the users prefix. Like:

http://example.com/username

instead of

http://example.com/users/1

解决方案

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屋!

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