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

Ruby on Rails 5.2.0路由映射:将users资源路由映射至根路径

解决Rails 5.2.0中Users资源映射到根路径的问题

嘿,这事儿好办!你只需要调整routes.rb里的资源配置和根路由设置,就能把users资源的请求直接映射到应用根路径。

修改后的routes.rb代码:

Rails.application.routes.draw do
  devise_for :users
  
  # 保留你原来的其他路由(如果还需要访问的话)
  get 'landing/index'
  get 'welcome/index'

  # 将users资源的路径指定为根路径 '/'
  resources :users, path: '/'

  # 把根路由指向users#index,替换原来的landing#index
  root to: 'users#index'
end

关键说明:

  • resources :users, path: '/':这行代码会把users资源的所有RESTful路由都映射到根路径下,比如:
    • GET / → users#index(代替原来的/users)
    • GET /new → users#new(代替原来的/users/new)
    • 其他如/1对应users#show、/1/edit对应users#edit等也会自动映射到根路径下的对应路径
  • root to: 'users#index':确保访问应用根路径localhost:3000/时,直接触发UsersController的index动作,和上面的资源配置配合完成你的需求。

注意事项:

如果你的landing#index页面还需要单独访问(比如通过/landing/index),那保留get 'landing/index'就没问题;如果不需要了,也可以删掉这行。另外,路由的顺序很重要,devise_for :users要放在前面,避免和其他路由冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:39:38