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

Rails路由异常:查询到用户仍重定向至dashboard页面

问题分析:访问用户详情页时已查到用户却仍被重定向

可能的原因及解决方案

1. 实际@user为nil,你误判查询结果

控制台仅显示执行了查询SQL,不代表存在匹配的用户记录。比如当id=2的用户在数据库中不存在时,User.find_by_id(params[:id])会返回nil,触发show方法中的重定向逻辑。

验证方法:在set_user方法中添加日志,确认@user的实际值:

def set_user
  @user = User.find_by_id(params[:id])
  Rails.logger.info "当前查询到的用户: #{@user.inspect}"
end

重新访问localhost:3000/2后查看日志,如果输出为当前查询到的用户: nil,说明确实没有找到用户,需要检查数据库中是否存在id=2的用户。

2. 全局身份验证拦截未被正确跳过

如果你的ApplicationController中定义了全局的before_action :authenticate_user!,那么DashboardController中before_action :authenticate_user!, except: [:show]的写法不会覆盖父类的全局拦截,而是追加了一个新的拦截规则。此时未登录用户访问show动作时,会被父类的authenticate_user!重定向到根路径(即dashboard)。

解决方法:在DashboardController中明确跳过父类的身份验证拦截:

class DashboardController < ApplicationController
  # 替换原来的before_action :authenticate_user!
  skip_before_action :authenticate_user!, only: [:show]
  before_action :set_user, only: [:show]

  # ... 其余代码保持不变
end

3. 确认重定向的实际来源

可以在控制台日志中查看是否有类似Filter chain halted as :authenticate_user! rendered or redirected的提示,这能直接告诉你重定向是来自身份验证拦截还是show方法中的逻辑。


内容的提问来源于stack exchange,提问作者A-laz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:35:09