You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails自定义Devise默认URL:移除/new和/edit并设置替代路径

在Ruby on Rails中自定义Devise的URL路径

要修改Devise默认生成的带/new、/edit的URL,同时保证项目正常运行,你可以通过自定义路由实现,具体步骤如下:

1. 跳过Devise默认路由

首先在config/routes.rb中,跳过你需要自定义的Devise模块(比如注册、密码重置等)的默认路由,避免和自定义路由冲突:

# 跳过注册模块的默认路由,可根据需求替换为:passwords、:sessions等模块
devise_for :users, skip: [:registrations]

2. 自定义路由映射

使用devise_scope :user块重新定义对应的路由,将目标URL直接指向Devise控制器的动作,移除多余的/new、/edit路径:

devise_scope :user do
  # 注册页面:将 /users/sign_up/new 改为 /users/sign_up
  get '/users/sign_up', to: 'devise/registrations#new', as: :new_user_registration
  # 提交注册表单
  post '/users', to: 'devise/registrations#create', as: :user_registration
  
  # 编辑用户信息:可将默认的 /users/edit 改为自定义路径(比如 /users/profile)
  get '/users/profile', to: 'devise/registrations#edit', as: :edit_user_registration
  # 更新用户信息
  patch '/users', to: 'devise/registrations#update'
  put '/users', to: 'devise/registrations#update'
  # 删除用户
  delete '/users', to: 'devise/registrations#destroy'
end

3. 验证路由正确性

运行以下命令检查生成的路由,确保所有动作都正确映射到目标URL,且没有冲突:

rails routes

4. 确保视图路径助手正常工作

Devise视图中默认使用路径助手(比如new_user_registration_path),自定义路由时已经通过as: :new_user_registration保留了原助手名,因此视图中的链接、表单会自动指向新URL,无需额外修改。

其他场景示例

如果需要修改密码重置的URL(比如把/users/password/new改为/users/forgot-password),用同样的方法即可:

devise_for :users, skip: [:passwords]

devise_scope :user do
  get '/users/forgot-password', to: 'devise/passwords#new', as: :new_user_password
  post '/users/forgot-password', to: 'devise/passwords#create', as: :user_password
  get '/users/reset-password', to: 'devise/passwords#edit', as: :edit_user_password
  patch '/users/reset-password', to: 'devise/passwords#update'
  put '/users/reset-password', to: 'devise/passwords#update'
end

内容的提问来源于stack exchange,提问作者Fernando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:54:59