Rails技术问题:如何在一个模型控制器中引用另一模型的路径?
问题解决步骤
1. 确认路由配置
首先确保你的config/routes.rb里已经正确定义了Score的资源路由:
resources :scores
执行rails routes命令可以查看所有路由助手,确认new_score_path存在(对应GET请求/scores/new)。
2. 修正重定向代码
你的redirect_to写法错误,导致路由参数被当成查询字符串传递。把这行:
format.html { redirect_to url: new_scores_path, notice: 'Prediction WAS successfully created.' }
改成:
format.html { redirect_to new_score_path, notice: 'Prediction was successfully created.' }
错误原因说明
当你使用redirect_to url: new_score_path时,Rails会将url:视为查询参数的键,而非重定向的目标路径。此时Rails默认跳转到当前控制器(Predictions)的index页面,并把url和notice作为URL查询参数附加,这就是你看到地址栏出现http://localhost:3000/predictions?notice=...&url=%2Fscores%2Fnew的原因。
3. 额外优化(非必需)
你代码中更新用户lastcase的部分可以简化,不需要重新查询用户:
# 替换原来的user查询和保存代码 @current_user.update(lastcase: @current_user.lastcase + 1)
内容的提问来源于stack exchange,提问作者GhostRider
相关产品推荐
相关产品推荐

