Rails结合devise实现自定义用户个人页URL 替换默认带ID路径问题
步骤1:配置路由规则
打开config/routes.rb,按以下规则修改:
- 保留原有devise路由声明的前提下,新增自定义个人主页路由,可同时禁用默认的users资源show路由,防止旧路径仍然可访问:
# 原有devise路由 devise_for :users # 禁用users默认show路由 resources :users, except: [:show] # 自定义个人主页路由 get '/my-profile', to: 'users#show', as: :my_profile
如果你需要保留其他用户的公开个人主页功能,可以省略
except: [:show]的配置,不影响自定义路径的使用。
如果后续需要配置购物车同类路径,按照同样格式新增即可:
get '/my-cart', to: 'carts#show', as: :my_cart
步骤2:调整控制器逻辑
打开app/controllers/users_controller.rb,修改show方法的查询逻辑,不再从URL参数取id,直接取当前登录用户:
class UsersController < ApplicationController # 确保访问个人页必须登录 before_action :authenticate_user!, only: [:show] def show # 直接取当前登录用户,无需依赖URL参数的id @user = current_user # 原有业务逻辑保留即可 end end
如果是购物车的对应控制器,修改逻辑同理:
class CartsController < ApplicationController before_action :authenticate_user!, only: [:show] def show @cart = current_user.cart end end
步骤3:替换全局路径引用
- 将项目中所有原来调用
user_path(@user)的位置,全部替换为my_profile_path - 如需修改登录后默认跳转地址,在
app/controllers/application_controller.rb中重写devise的跳转方法:
class ApplicationController < ActionController::Base def after_sign_in_path_for(resource) my_profile_path end end
验证配置是否生效
执行rails routes命令查看路由列表,确认存在my_profile路由且路径为/my-profile,访问旧路径/users/:id会返回404,访问/my-profile会正常展示当前登录用户的信息即为配置成功。
内容的提问来源于stack exchange,提问作者looping124
相关产品推荐
相关产品推荐

