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

Rails项目Admins命名空间下用户history路由配置问题咨询

问题原因

你当前配置的get '/users/history', to: 'users#history'是集合路由,仅匹配/admins/users/history路径,没有预留用户ID的参数位,你传入的user.id会被Rails识别为格式(format)参数,所以最终生成的路径是/admins/users/history.1,不符合预期。

正确配置步骤

1. 修改路由配置

替换config/routes.rb中admins命名空间下的users相关路由,使用成员路由绑定单个用户资源:

namespace :admins do
  resources :users, only: %i[index show edit update] do
    member do
      # 成员路由会自动拼接用户ID,生成路径 /admins/users/:id/history
      get :history
    end
  end
  # 保留原有其他路由
  resources :calculators, only: %i[new create edit update]
end

注意:删除你原来写的get '/users/history', to: 'users#history',同时把history从resources :users的only数组中移除,因为Rails默认资源动作不包含自定义的history方法

2. 更新视图中的路由调用

修改index.html.slim中历史记录跳转的路径方法,路由生成助手会自动变更为history_admins_user_path:

td = link_to fa_icon('history'), history_admins_user_path(user)

3. 可选优化:清理控制器冗余代码

你已经为UsersController配置了before_action :find_user, except: [:index],会自动为edit、update、history动作初始化@user实例,所以可以删掉这三个动作里重复的@user = User.find(params[:id])代码,减少不必要的重复查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:24:06